安卓开发之ImageView变形的处置
安卓开发之ImageView变形的处理
当页面布局有ImageView的时候会出现适配比例不当而变形的情况,解决办法是自己复写一个ImageView,代码如下:
public class XImageView extends ImageView { float arg = .0f; public XImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSize = MeasureSpec.getSize(widthMeasureSpec); float ft = arg == 0f ? 0.75f : arg; setMeasuredDimension(widthSize, (int) (widthSize * ft)); } @Override protected void onFinishInflate() { super.onFinishInflate(); CharSequence charSequence = getContentDescription(); if (!TextUtils.isEmpty(charSequence)) { try { arg = Float.parseFloat(charSequence.toString()); } catch (Exception e) { } } } @Override public void setImageBitmap(Bitmap bm) { if (arg == 0f && bm != null) { arg = 1f * bm.getHeight() / bm.getWidth(); } super.setImageBitmap(bm); } }
其中setImageBitmap首先计算出了实际图片的宽高比例,并赋值给arg,然后将arg传给onMeasure,float ft = arg == 0f ? 0.75f : arg;这句话是我的项目中默认图片的宽高比是4:3,如果没有这个要求可以直接float ft = arg,然后在setMeasuredDimension(widthSize, (int) (widthSize * ft));这句话就是根据宽度的大小等比例设置高度的大小,这样图片就是等比例缩放了,不会出现变形的情况了。