自定义可绘制形状 android

Custome drawable Shape android

任何人都知道如何在 android 中制作这种自定义形状的可绘制视图。

这取决于您希望此视图如何缩放,但是这个怎么样?

public class WeirdView extends View {

    private Paint red;
    private Paint white;

    public WeirdView(Context context) {
        super(context);
        initDrawingComponents();
    }

    private void initDrawingComponents() {
        red = new Paint(Paint.ANTI_ALIAS_FLAG);
        red.setColor(0xFFFF0000);
        white = new Paint(Paint.ANTI_ALIAS_FLAG);
        white.setColor(0xFFFFFFFF);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float width = getWidth();
        float height = getHeight();
        float horizontalLinePos = height * 0.25f;
        float leftCircleRadius = height * 0.25f;
        float rightCircleRadius = width * 0.15f;
        float rightCircleBorderDist = width * 0.12f;

        canvas.drawRect(0, 0, leftCircleRadius, horizontalLinePos + leftCircleRadius, red);
        canvas.drawCircle(leftCircleRadius, horizontalLinePos + leftCircleRadius, leftCircleRadius, white);
        canvas.drawRect(0, 0, width - rightCircleBorderDist, horizontalLinePos, red);
        canvas.drawCircle(width - rightCircleBorderDist, horizontalLinePos - rightCircleRadius, rightCircleRadius, red);
    }
}

这与您在此处发布的图片非常相似。

创建一个 XML 文件并将其放在 drawable 文件夹中。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:right="100dp">
        <shape android:shape="rectangle">
            <size
                android:width="100dp"
                android:height="100dp" />
            <solid android:color="#F40D20" />
        </shape>
    </item>

    <item android:left="100dp">
        <shape android:shape="rectangle">
            <size
                android:width="100dp"
                android:height="100dp" />
            <solid android:color="#FFFFFFFF" />
        </shape>
    </item>

    <item android:top="100dp">
        <shape android:shape="rectangle">
            <size
                android:width="100dp"
                android:height="100dp" />
            <solid android:color="#FFFFFFFF" />
            <corners android:topLeftRadius="30dp" />
        </shape>

    </item>

    <item android:bottom="100dp">
        <shape android:shape="rectangle">
            <size
                android:width="100dp"
                android:height="100dp" />
            <solid android:color="#F40D20" />
            <corners android:bottomRightRadius="30dp" />
        </shape>
    </item>
</layer-list>

结果:

Radius 更改为您想要的外观。