在Android的XML drawable资源中,我们可以通过shape标签定义各种图形,当需要给图形添加渐变效果时,gradient标签是核心配置项,其中startColor属性就是用来设置渐变起始颜色的关键属性。

startColor属性的基本语法
startColor是<gradient>标签的子属性,直接写在<gradient>标签内部即可,其取值为颜色值,支持多种常见的Android颜色格式。
基础配置结构如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FF0000"
android:endColor="#0000FF" />
</shape>
startColor支持的颜色格式
startColor的颜色值可以是以下几种形式:
- 十六进制ARGB格式:比如#FFFF0000,前两位表示透明度,后面六位分别是红、绿、蓝通道值,透明度FF为完全不透明,00为完全透明。
- 十六进制RGB格式:比如#FF0000,省略透明度通道,默认完全不透明。
- 资源引用格式:如果颜色定义在res/values/colors.xml中,可以通过@color/颜色名的方式引用,例如android:startColor="@color/red"。
颜色格式示例
<!-- 定义在colors.xml中的颜色 -->
<color name="gradient_start">#33FF5722</color>
<!-- shape中引用该颜色 -->
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="@color/gradient_start"
android:endColor="#FF2196F3" />
</shape>
搭配其他属性实现不同渐变效果
startColor通常需要和gradient的其他属性配合使用,才能实现符合预期的渐变效果:
| 属性名 | 作用说明 |
|---|---|
| android:endColor | 设置渐变的结束颜色,和startColor配合定义渐变的范围 |
| android:centerColor | 可选属性,设置渐变的中间颜色,实现三色渐变效果 |
| android:type | 设置渐变类型,可选linear(线性渐变,默认)、radial(径向渐变)、sweep(扫描渐变) |
| android:angle | 仅线性渐变有效,设置渐变角度,必须是45的倍数,0表示从左到右,90表示从下到上 |
| android:gradientRadius | 仅径向渐变有效,设置渐变的半径 |
线性渐变示例
实现从左到右的红色到蓝色线性渐变:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FFFF0000"
android:endColor="#FF0000FF"
android:type="linear"
android:angle="0" />
</shape>
径向渐变示例
实现从中心红色向外蓝色扩散的径向渐变:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FFFF0000"
android:endColor="#FF0000FF"
android:type="radial"
android:gradientRadius="100dp" />
</shape>
三色渐变示例
实现红、黄、蓝三色渐变:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FFFF0000"
android:centerColor="#FFFFFF00"
android:endColor="#FF0000FF"
android:type="linear"
android:angle="0" />
</shape>
使用注意事项
1. 如果只设置了startColor而没有设置endColor,渐变效果不会生效,至少需要同时设置startColor和endColor两个属性。
2. 当type设置为radial时,必须同时设置gradientRadius属性,否则会抛出运行时异常。
3. angle属性仅在type为linear时生效,设置其他渐变类型时该属性会被忽略。
4. 颜色值中的字母大小写不敏感,#ff0000和#FF0000是等效的。
通过以上配置方式,我们可以灵活设置Android shape gradient的起始颜色,结合不同的渐变类型和属性,就能实现各种符合UI设计要求的渐变效果。
AndroidshapegradientstartColorXML修改时间:2026-06-24 04:39:20