如何绘制具有可变描边宽度的 Android Shape 矩形

How to draw a Android Shape Rectangle with variable stroke width

我想画一个有洞的矩形。我正在尝试通过使用 Shape Rectangle 来实现这一点。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="50dp"
        android:color="@color/red" />
</shape>

我想弄清楚如何在绘制此矩形时更改笔划宽度,以便矩形应具有例如:顶部和底部边缘的笔划宽度为 50 dp,而左右边缘的笔划宽度为 20 dp。

非常感谢你在这方面的帮助。

我假设形状用作视图的背景(例如 imageView)。 所以先从imageView中获取Drawable对象,再从中获取Paint对象。然后你可以修改任何你想要的属性。

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    // cast to 'ShapeDrawable'
    ShapeDrawable shapeDrawable = (ShapeDrawable)background;
    shapeDrawable.getPaint().setStrokeWidth(...);
}

相关问题在这里:Set android shape color programmatically

这是一个如何使用图层列表进行操作的示例:我将像这样更改左上角和右上角的属性:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>

    <item android:top="1dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/holo_blue_bright"/>
        </shape>
    </item>

    <item android:left="3dp">
        <shape android:shape="rectangle">
            <gradient android:angle="270" android:startColor="#8C2300" android:endColor="#D34617"/>
        </shape>
    </item>

    <item android:right="8dp">
        <shape android:shape="rectangle">
            <gradient android:angle="270" android:startColor="#000000" android:endColor="#ffc0cb"/>
        </shape>
    </item>

</layer-list>

在您的可绘制文件夹中将此文件命名为 layers.xml。然后像这样将它作为背景应用到您的视图中:

android:background="@drawable/shape"

感谢大家的帮助。我最终覆盖了 onDraw() 以清除布局的背景颜色以使用 set Xfermode() 创建矩形孔。