如何在android中制作渐变背景

新手上路,请多包涵

我想创建渐变背景,渐变位于上半部分,下半部分为纯色,如下图所示:

我不能因为 centerColor 展开覆盖底部和顶部。

在按钮的渐变中,一条白色的水平线在蓝色上向顶部和底部逐渐消失。

如何制作像第一张图片一样的背景?我怎样才能使小的 centerColor 没有散开?

这是上面背景按钮的 XML 中的代码。

 <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <gradient
        android:startColor="#6586F0"
        android:centerColor="#D6D6D6"
        android:endColor="#4B6CD6"
        android:angle="90"/>
    <corners
        android:radius="0dp"/>

</shape>

原文由 kongkea 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 886
2 个回答

您可以通过使用 xml 图层列表 将顶部和底部“带”组合到一个文件中来创建这种“半渐变”外观。每个波段都是一个 xml 形状。

有关详细教程,请参见之前关于 SO 的答案: 多渐变形状

原文由 onosendai 发布,翻译遵循 CC BY-SA 3.0 许可协议

视觉示例有助于解决此类问题。

样板

为了创建渐变,您在 res/drawable 中创建一个 xml 文件。我打电话给我 _的 my_gradientdrawable.xml

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:angle="0"
        android:startColor="#f6ee19"
        android:endColor="#115ede" />
</shape>

您将其设置为某个视图的背景。例如:

 <View
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:background="@drawable/my_gradient_drawable"/>

类型=“线性”

angle 设置为 linear 类型。它必须是 45 度的倍数。

 <gradient
    android:type="linear"
    android:angle="0"
    android:startColor="#f6ee19"
    android:endColor="#115ede" />

在此处输入图像描述

类型=“径向”

gradientRadius 设置为 radial 类型。使用 %p 意味着它是父级最小尺寸的百分比。

 <gradient
    android:type="radial"
    android:gradientRadius="10%p"
    android:startColor="#f6ee19"
    android:endColor="#115ede" />

在此处输入图像描述

类型=“扫”

我不知道为什么有人会使用扫描,但为了完整起见,我将其包括在内。我不知道如何改变角度,所以我只包括一张图片。

 <gradient
    android:type="sweep"
    android:startColor="#f6ee19"
    android:endColor="#115ede" />

在此处输入图像描述

中央

您还可以更改扫描或径向类型的中心。这些值是宽度和高度的分数。您也可以使用 %p 表示法。

 android:centerX="0.2"
android:centerY="0.7"

在此处输入图像描述

原文由 Suragch 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题