在圆圈内绘制正方形布局

Drawing a square layout inside a circle

我想在一个圆圈内做一个相对布局,即相对布局应该如下图所示的正方形。

我正在尝试将布局的宽度和高度设置为:

√((diameter)²/2) 大约是 70 %


(来源: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>

这是我得到解决方案的方法。首先,我创建了一个方形框架来容纳所有布局。

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>

这是我得到的 正方形,不是长方形。