在安卓中设置描边渐变

12

我有一个圆形的可绘制对象,在其中设置了8dp的白色描边,类似于这样:

    circleImage = (ImageView) rootView.findViewById(R.id.image);
    circleImage.setOnClickListener(clickListener);
    drawable = (GradientDrawable) circleImage.getBackground();
    drawable.setStroke(8, getResources().getColor(R.color.colorWhite));

circleImage 的 XML 如下所示:

 <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_centerInParent="true"
            android:id="@+id/image"
            android:background="@drawable/roundcorner"
            android:clickable="true"/>
我现在想做的是更改drawable.setStroke,使其包含像这样的渐变色:

1

我想最简单的方法是在drawable XML中编写一些内容,但我不太知道如何实现。

roundcorner.xml

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"  android:shape="rectangle" >
        <corners
            android:topLeftRadius="100dp"
            android:topRightRadius="100dp"
            android:bottomLeftRadius="100dp"
            android:bottomRightRadius="100dp"
            />
        <padding
            android:left="2dp"
            android:top="2dp"
            android:right="2dp"
            android:bottom="2dp"
            />
        <size
            android:width="100dp"
            android:height="100dp"
            />
    </shape>
2个回答

34

你应该像这样做。使用layer-list和两个形状。第一个用于渐变描边,第二个用于实心填充。

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="oval" >
            <gradient
                android:angle="360"
                android:startColor="#543456"
                android:endColor="#ff00b5"
                android:type="linear" />
            <size android:width="24dp"
                  android:height="24dp"/>
        </shape>
    </item>

    <item
        android:bottom="2dp"
        android:left="2dp"
        android:right="2dp"
        android:top="2dp">
        <shape android:shape="oval" >
            <solid android:color="#fff" />
        </shape>
    </item>

</layer-list>

这段代码看起来像这样enter image description here


6
如果您需要内部颜色是透明的,那么可以使用圆形形状:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:thickness="2dp"
    android:useLevel="false">
    <gradient
        android:startColor="@color/sea_green"
        android:endColor="@color/black"
        android:angle="270" />
</shape>

enter image description here


3
如何用矩形获得相同的效果? - I.Step
@I.Step,也许尝试使用android:shape="rectangle" - pckill
1
是的,但使用矩形你不会得到边框,而是得到一个矩形。如果你尝试用两个矩形来制作边框,其中一个矩形有一点填充,另一个没有,那么当内部矩形具有透明背景时,它将无法正常工作。 - I.Step

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接