Android中如何使控件保持固定宽高比

如何实现固定的宽高比,现在提供两种方案。

1. 自定义view

自定义RatioView,重写onMeasure或onLayout等相关方法,通过预定的比例计算宽高。

代码:

public class RatioView extends View {

    private int mRatio=2;

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

    public RatioView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public RatioView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width=MeasureSpec.getSize(widthMeasureSpec);
        if(mRatio!=0){
        	//根据宽度求高度
            int height=width/2;
            //根据宽度求高度	
		  heightMeasureSpec=MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

布局代码

 <com.gas.test.widget.RatioView
        android:id="@+id/ratio_rv"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#30ff0000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
2. ConstraintLayout的DimensionRatio

代码如下:

 <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/ratio_rv">

        <TextView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#300000ff"
            app:layout_constraintDimensionRatio="2:1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

constraintDimensionRatio="H,1:2"中的 W or H 指后面比例的第1个是那个方向的,默认是W(即宽度)第一个。

上图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值