美文网首页
宽高相等的布局

宽高相等的布局

作者: 我不想说 | 来源:发表于2019-11-08 15:19 被阅读0次

让高度等于宽度的正方形图片布局

image.png

public class MyLayout extends RelativeLayout {

public MyLayout(Context context, AttributeSet attrs,
                int defStyle) {
    super(context, attrs, defStyle);
}

public MyLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

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

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
            getDefaultSize(0, heightMeasureSpec));

    int childWidthSize = getMeasuredWidth();
    // 高度和宽度一样
    heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(
            childWidthSize, MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

}

宽高相等的图片
使用:

<....MyLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">
    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/iv_home_quanbushangpin" />
</....MyLayout>

相关文章

网友评论

      本文标题:宽高相等的布局

      本文链接:https://www.haomeiwen.com/subject/yqxwbctx.html