在圆内绘制正方形布局

8
我正在尝试让相对布局在圆内限制,即相对布局应该像下图所示的正方形一样。
我正在尝试设置布局的宽度和高度为:
√((直径)²/2),约为70% square inside a circle (来源:yogaflavoredlife.com)
public class SquareLayout extends RelativeLayout {
    public SquareLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
        int originalHeight = MeasureSpec.getSize(heightMeasureSpec);
        int required = Math.min(originalWidth, originalHeight) * 7 / 10;

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(required, required);
    }
}

我得到的是矩形布局而不是正方形布局:

请问有人可以指导我错在哪里吗?

示例用法:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <com.example.widget.SquareLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F55C5C">

    </com.example.widget.SquareLayout>

</RelativeLayout>

我尝试了你的代码,但是我得到了一个正方形,可能与附近的其他视图有关。 - Farhan C K
我得到了一个矩形的。 - Samir
你能提供完整的SquareFrameInsideCircle视图吗?我认为这与正方形高度不匹配圆形高度有关。特别是因为你使用了super.onMeasure(widthMeasureSpec, heightMeasureSpec);而不是传递所需的参数。 - se_bastiaan
抱歉,类名写错了。应该是同一个SquareLayout。请查看更新后的示例用法。 - Samir
1个回答

1
这是我得到解决方案的方法。首先,我创建了一个正方形框架来容纳所有的布局。
public class SquareFrame extends FrameLayout {
    public SquareFrame(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
        int originalHeight = MeasureSpec.getSize(heightMeasureSpec);
        int required = Math.min(originalWidth, originalHeight);

        super.onMeasure(
            MeasureSpec.makeMeasureSpec(required, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(required, MeasureSpec.EXACTLY));
    }
}

然后将所有布局插入到那个正方形框架中。
<com.example.widget.SquareFrame 
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#5CF5FC">

    <com.example.widget.SquareLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F55C5C">

    </com.example.widget.SquareLayout>

</com.example.widget.SquareFrame>

这是我得到的: 一个正方形,而不是矩形。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接