android设置自定义view的宽高达到设计图比例一致的效果

这个控件是根据设计图的宽高比来设置该view在手机上的宽高,从而达到跟设计图的比例一致的效果。如果你的项目做了屏幕适配,那应该不需要这个view,但如果做了屏幕适配,也不会来搜这个话题了吧?[滑稽]

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import com.makeramen.roundedimageview.RoundedImageView;

/**
 * 根据设计图的宽高比来设置对应view在某手机上的宽高
 *
 * @author ly
 * date 2020/4/14 14:50
 */
public class ScreenRatioRoundedImageView extends RoundedImageView {

    private int viewW, viewH;

    public ScreenRatioRoundedImageView(Context context) {
        this(context, null);
    }

    public ScreenRatioRoundedImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScreenRatioRoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.ScreenRatioRoundedImageView);
        float widthScreenRatio = attr.getFloat(R.styleable.ScreenRatioRoundedImageView_widthScreenRatio, 1);
        float whRatio = attr.getFloat(R.styleable.ScreenRatioRoundedImageView_whRatio, 1);
        attr.recycle();

        viewW = (int) (ScreenUtil.getScreenWidth() * widthScreenRatio);
        viewH = (int) (viewW / whRatio);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureW(widthMeasureSpec), measureH(heightMeasureSpec));
    }

    private int measureW(int widthMeasureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = viewW;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    private int measureH(int heightMeasureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = viewH;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    public int getViewW() {
        return viewW;
    }

    public void setViewW(int viewW) {
        this.viewW = viewW;
    }

    public int getViewH() {
        return viewH;
    }

    public void setViewH(int viewH) {
        this.viewH = viewH;
    }
}

attr:

 
        
        
        
        
 

使用该view的时候从外部传入设计图上的widthScreenRatio及whRatio即可。

最后,还是建议做一下屏幕适配的,嫌宽高限定符和最小宽度限定符适配方案麻烦的可以考虑用今日头条的屏幕适配方案。我自己的项目以后也会采用今日头条的适配方案。

end

你可能感兴趣的:(android)