Android View设置宽高比

  • 直接上代码(代码可直接复制使用)
1、布局设置

ConstraintLayout 有个属性可以控制比例:layout_constraintDimensionRatio




    
    

image.png
2、代码设置
//根据宽高比设置控件宽高, 如设置宽高比为5:4,那么widthRatio为5,heightRatio为4
public static void setWidthHeightWithRatio(View view, int width, int widthRatio, int heightRatio) {
    if (width <= 0) width = view.getWidth();
    int height = width * heightRatio / widthRatio;
    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
    if (layoutParams != null) {
        layoutParams.height = height;
        layoutParams.width = width;
        view.setLayoutParams(layoutParams);
    }
}
3、自定义控件式
  • 新建RatioRelativeLayout 继承RelativeLayout
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

/**
 * 自定义高宽比布局
 */
public class RatioRelativeLayout extends RelativeLayout {

    private float ratio;

    public RatioRelativeLayout(Context context) {
        super(context);
    }

    public RatioRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取自定义属性值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioRelativeLayout);
        ratio = typedArray.getFloat(R.styleable.RatioRelativeLayout_ratio, 0.0f);
    }

    public RatioRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取宽度的模式和尺寸
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        if (ratio != 0) {
            //根据宽高比ratio和模式创建一个测量值
            heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (widthSize * ratio), MeasureSpec.EXACTLY);
        }
        //必须调用下面的两个方法之一完成onMeasure方法的重写,否则会报错
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 设置高宽比
     *
     * @param ratio 宽高比(比如:高:宽 = 4:5,ratio=0.8)
     */
    public void setRatio(float ratio) {
        this.ratio = ratio;
    }
}

  • 在styles.xml文件中添加自定义属性
 
        
    
  • 使用
       

你可能感兴趣的:(Android View设置宽高比)