从一件小事说起,我们的UI姐姐,给的是PX的图片,Android分辨率又多,这尼玛肯定会变形,如何保证让这个图片不变形,又更加优雅的处理呢,
我可以根据宽去自适应高度啊(因为我的宽度是根据权重来的,得到了权重测量的宽度后,这里我就可以把高度按照一定比例缩放就可以了),可以按照UI姐姐给的PX的图片去
相应的去适应屏幕
很简单,但是很不错的处理方案
public class MagicHeightImageView extends ImageView{ private int mScream; private int scaleH; private int scaleW; public MagicHeightImageView(Context context) { this(context ,null); } public MagicHeightImageView(Context context, AttributeSet attrs) { this(context, attrs , 0); } public MagicHeightImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mScream = ScreenUtils.getScreenWidth(context); TypedArray ta = context.getTheme().obtainStyledAttributes(attrs , R.styleable.MagicHeightImageView , defStyleAttr ,0); int count = ta.getIndexCount(); for (int i = 0 ;i < count ; i++ ){ int attr = ta.getIndex(i); switch (attr){ case R.styleable.MagicHeightImageView_magic_h: scaleH = ta.getInteger(attr , 1); break; case R.styleable.MagicHeightImageView_magic_w: scaleW = ta.getInteger(attr , 1); break; } } ta.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width = widthSize ; int height = widthSize * scaleH / scaleW ; setMeasuredDimension(width , height); } }
使用
xmlns:app="http://schemas.android.com/apk/res-auto"
<com.example.administrator.widget.MagicHeightImageView android:id="@+id/iv_qfcf" android:layout_width="0dp" android:layout_weight="1" app:magic_w="163" 这里是UI给的宽度的px app:magic_h="200" 这里是UI给的高度的px android:background="@drawable/img_qfcf" android:gravity="center" android:layout_height="match_parent" />