文章目录
gradient属性简介
在drawable文件夹中创建shape_gradient.xml资源。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
android:angle="integer"
android:centerX="integer"
android:centerY="integer"
android:centerColor="integer"
android:endColor="color"
android:gradientRadius="integer"
android:startColor="color"
android:type=["linear" | "radial" | "sweep"]
android:useLevel=["true" | "false"] />
</shape>
[shape] 根标签,声明一个shape [gradient] 声明该shape的属性-渐变色,除此外还有其他属性如corners、stroke、size等等
android:type
String 值
只有三种类型
- linear是线性[线性渐变.可以理解为 y=kx+b.]
- radial是由中心向外渐变的[圆形渐变,起始颜色从cenralX,centralY点开始。]
PS: 设置这种类型如果没有设置android:gradientRadius,会报错。
- sweep是梯形的[扫描线渐变]
android:angle
Integer 值
代表渐变颜色的角度,0 从左往右,90 从上往下(必须是45的整数倍)。
当angle为0时,颜色渐变方向是从左往右; 当angle为90时,颜色渐变方向是从下往上; 当angle为180时,颜色渐变方向是从右往左; 当angle为270时,颜色渐变方向是从上往下;
PS:默认是 0,而且该属性只有在type="linear"情况下起作用。
android:startColor
Color 值
颜色渐变的开始颜色
android:endColor
Color 值
颜色渐变的结束颜色
android:centerColor
Color 值
颜色渐变的中间颜色,主要用于多彩。
android:centerX
Float 值(0 ~ 1.0)
相对于X的渐变位置
PS:这个属性只有在type不为linear时起作用
android:centerY
Float 值(0 ~ 1.0)
相对于Y的渐变位置
PS:这个属性只有在type不为linear时起作用
android:gradientRadius
Float 值
渐变颜色的半径,单位是像素(不需要写单位)
PS:此属性需要配置type="radial"。
android:useLevel
Boolean 值
如果为true,则可在LevelListDrawable中使用。
这通常应为“false”,否则形状不会显示!
代码片段
shape_gradient_one.xml
从左往右线性渐变
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="0"
android:endColor="@android:color/transparent"
android:startColor="@android:color/holo_red_light"
android:type="linear"
android:useLevel="false" />
</shape>
shape_gradient_two.xml
中心,半径为75的圆形渐变
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:centerColor="@android:color/black"
android:centerX="0.5"
android:centerY="0.5"
android:endColor="@android:color/white"
android:gradientRadius="75"
android:startColor="@android:color/holo_red_dark"
android:type="radial" />
</shape>
shape_gradient_three.xml
中心,半径为75的扫描渐变
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:centerColor="@android:color/black"
android:centerX="0.5"
android:centerY="0.5"
android:endColor="@android:color/white"
android:gradientRadius="75"
android:startColor="@android:color/holo_red_dark"
android:type="sweep" />
</shape>
