安卓开发之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));这句话就是根据宽度的大小等比例设置高度的大小,这样图片就是等比例缩放了,不会出现变形的情况了。
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28