在 Android 中制作自定义可绘制形状

Make Custom Drawable Shape in Android

我想像下面这样绘制,

我可以在两个不同的 xml 文件中制作矩形和三角形。但是我想把它们联合起来做成这样的可绘制对象。

我希望您在 Tabular 导航器或 ViewPager 中需要它。我的建议是

1)使用矩形作为所有案例的背景。

2)为未选中的项目创建相同的三角形可绘制对象,但使用背景颜色(白色或透明)。

3)为所有项目创建一个带有三角形背景的视图

4)根据选择状态手动​​setVisibility三角视图

为此使用 <layer-list/>

举个例子。

在项目目录resDrawable文件夹中, 制作 xml 文件并将其命名为 layerlist.xml 并根据您的要求将其粘贴到代码下方。 您还可以在示例中的 <item/> 标记中添加可绘制形状而不是可绘制形状。并以此 xml 作为 ImageView 的背景。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <bitmap android:src="@drawable/android_red"
        android:gravity="center" />
    </item>
    <item android:top="10dp" android:left="10dp">
      <bitmap android:src="@drawable/android_green"
        android:gravity="center" />
    </item>
    <item android:top="20dp" android:left="20dp">
      <bitmap android:src="@drawable/android_blue"
        android:gravity="center" />
    </item>
</layer-list>

这里是使用<layer-list/>的结果。

希望对你有所帮助...

使用 layer-list 制作此自定义形状 drawable

/res/drawable/custom_shape.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Transparent Rectangle -->
    <item>
        <shape android:shape="rectangle">
            <size
                android:width="300dp"
                android:height="60dp" />
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <!-- Colored Rectangle -->
    <item
        android:bottom="20dp">
        <shape android:shape="rectangle">
            <size
                android:width="300dp"
                android:height="60dp" />
            <solid android:color="#9A8585" />
        </shape>
    </item>

    <!-- Bottom Triangle -->
    <item
        android:left="80dp"
        android:right="120dp"
        android:top="0dp"
        android:bottom="30dp">
        <rotate android:fromDegrees="45">
            <shape android:shape="rectangle">
                <solid android:color="#9A8585" />
            </shape>
        </rotate>
    </item>

    <!-- Top Border -->
    <item
        android:bottom="75dp">
        <shape android:shape="rectangle">
            <solid android:color="#EFC1B3" />
        </shape>
    </item>

</layer-list>

使用:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_shape"/>

输出:

希望对你有所帮助~