在渐变中添加百分比

12

我正在尝试使用XML渐变代码创建一个按钮。(因为我是新用户不能上传图片:( ) 这个图片在它的边缘有两种颜色和圆角。渐变开始的颜色将从整个渐变长度的15%开始,而结束的颜色将在渐变长度的75%结束。 我使用以下代码创建具有两种颜色的渐变:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item  >
    <shape  android:shape="rectangle">
        <gradient
    android:angle="-45"
    android:startColor="#64bcfb"
    android:endColor="#2f8fd4"
     android:type="linear"/>

        <corners android:radius="10dp" />
    </shape>
</item>
</layer-list>

问题在于我不知道如何添加渐变的起始百分比和结束百分比。我在以下链接中做了一些搜索:

banded background with two colors?

Gradients and shadows on buttons

这两个链接中都有一些解决方案,但对我来说不起作用。这些解决方案是关于创建一个只有两种颜色的简单条形图,但我想创建一个带有一些边缘角落的按钮。我也不能在我的应用程序中使用原始图像,因为我需要根据需要动态更改其颜色。是否有人有任何关于如何在渐变中添加百分比的想法呢?

1个回答

19

这篇文章相当古老,但没有答案,我认为我遇到了同样的问题并找到了解决方法。

如果你只需要一个有2种颜色、单一过渡并带圆角的渐变,你可以按照以下方式操作:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />
    <gradient
        android:angle="270"
        android:startColor="@android:color/transparent"
        android:centerColor="@android:color/transparent"
        android:centerY="0.65"
        android:endColor="@color/colorPrimary"
        android:type="linear" />
</shape>

这里的技巧是添加centerColorcenterY并修改它的中心位置,这将允许您修改过渡发生的位置。


刚刚成为对我有用的答案,centerY是我需要调整2色线性渐变“起点”的东西。谢谢! - the_dude_abides
很高兴能帮助到你 =) - Rui Cardoso

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