要保持imageView背景的纵横比,可以使用以下代码示例中的两种方法:
方法一:使用ScaleType属性
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.image); // 设置图片资源
// 设置ScaleType属性为CENTER_CROP,在保持纵横比的同时将图片缩放至ImageView的中心
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
方法二:自定义ImageView类
public class AspectRatioImageView extends ImageView {
public AspectRatioImageView(Context context) {
super(context);
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 获取ImageView的宽度和高度
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// 获取图片的宽度和高度
Drawable drawable = getDrawable();
if (drawable != null) {
int imageWidth = drawable.getIntrinsicWidth();
int imageHeight = drawable.getIntrinsicHeight();
if (imageWidth > 0 && imageHeight > 0) {
// 计算新的宽度和高度,保持纵横比
if (widthSize > 0) {
int newHeight = widthSize * imageHeight / imageWidth;
heightSize = Math.min(heightSize, newHeight);
} else if (heightSize > 0) {
int newWidth = heightSize * imageWidth / imageHeight;
widthSize = Math.min(widthSize, newWidth);
}
}
}
// 设置ImageView的宽度和高度
setMeasuredDimension(widthSize, heightSize);
}
}
在布局文件中使用自定义的AspectRatioImageView:
以上代码示例中的方法一使用了ImageView的ScaleType属性来设置图片的缩放类型,方法二则是通过自定义ImageView类来重新计算ImageView的宽度和高度,以保持图片的纵横比。