整体的背景颜色设置,使用的drawable中shape中gradient属性,背景色的最终样子:
首先介绍下gradient的相关属性:
<gradient
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"] />
linear属性使用:
angle属性针对type=linear的情况下有用,默认gradient为linear。
属性值为45的整数倍,
0:从左到右;90从下到上;270从上到下。
上面第一张效果图的gradient文件如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="0"
android:startColor="@color/splashStart"
android:centerColor="@color/splashCenter"
android:endColor="@color/splashEnd"
android:type="linear" />
</shape>
radial属性使用:
效果图如下:
属性设置为:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="90"
android:startColor="@color/splashStart"
android:centerColor="@color/splashCenter"
android:endColor="@color/splashEnd"
android:centerX="0.5"
android:centerY="0.5"
android:type="radial"
android:gradientRadius="800"/>
</shape>
type=radial 和 gradientRadius必须都要设置,否则编译报错。gradientRadius为圆形区域的半径大小;
参数 centerX 和 centerY 是设置X和Y轴的位置的百分比。
sweep属性使用:
效果图如下:
具体的属性定义:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="@color/splashStart"
android:centerColor="@color/splashCenter"
android:endColor="@color/splashEnd"
android:centerX="0.5"
android:centerY="0.8"
android:type="sweep" />
</shape>
和radial差不多,
canterX centerY控制 sweep属性的图片所在的x、y轴的位置百分比。
使用方式就是在res/drawable目录下建立my_gradient.xml文件,然后在需要使用的地方引用即可:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@drawable/splash_page_color_gradient">
当然,通过静态XML配置只能设置颜色较为简单的变化效果,如果需要设置复杂的颜色变化,那么就需要使用java代码动态设置了。请看gradient使用的下篇。
整个项目的下载地址: