MagicHeightImageView根据宽度自适应高度

从一件小事说起,我们的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" />




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值