【问题标题】:How to draw a Android Shape Rectangle with variable stroke width如何绘制具有可变笔触宽度的 Android 形状矩形
【发布时间】:2016-03-23 04:45:21
【问题描述】:

我想画一个有洞的矩形。我正在尝试通过使用 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。

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

【问题讨论】:

  • 我可能会查看图层列表,您可能会有更多的运气。我看不出用形状来做这件事。

标签: android android-canvas android-shape android-shapedrawable


【解决方案1】:

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

<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>

在你的drawable文件夹中调用这个文件,比如layers.xml。然后将其作为背景应用到您的视图中,如下所示:

android:background="@drawable/shape"

【讨论】:

    【解决方案2】:

    我假设,形状被用作视图的背景(例如 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

    【讨论】:

    • 感谢您的回复,但是如何更改矩形左右边缘的笔划宽度?
    • 我不知道这是否可能。也许你应该实现一个层列表,有一个矩形和 4 行。然后,您可以修改这些线的笔画值彼此不同。
    • 你能给我举个例子吗?那真的很有帮助。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2010-10-12
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多