本文讨论的是android中如何实现更平滑的单色渐变效果。一般来说,当我们想让界面上的某个区域呈现单色渐变效果,我们用drawable 来实现:
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:startColor="@android:color/holo_blue_light"
android:endColor="@android:color/transparent"
android:angle="180"
/>
<corners android:radius="10dp"/>
</shape>
上面定义如下属性
- 开始颜色,
- 结束颜色,
- 颜色渐变方向,上面定义的是垂直,从上到下

我们的效果是做面的图,这个效果在android上是最好实现的,因为xml就可以配置,中国特色使然,各种文档介绍也是上面雷同内容
。右边的背景如何实现呢?当时项目需要,找了很多文章都没有发现,最后是通过个View两个背景实现的,说实话当时蛮鄙视的,为什么
我们只会使用的,没有研究的动力、乐趣呢?
出于这样的自责,开始了进一步研究(不是网上有的我才会用,而是自我研究一些东西帮助大家),先看android是否有个给我们提供
机制帮我们实现这样的东西,看了几个Drawable paitDrawable、ShapeDrawalbe,最后发现通过PaintDrawable可以实现,结合
Shape的一些子类
<pre name="code" class="html">paintDrawable.setShaderFactory(new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
paintDrawable.setShaderFactory(new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient linearGradient = new LinearGradient(
width * x0,
height * y0,
width * x1,
height * y1,
stopColors, stopHeightsStep,
Shader.TileMode.CLAMP);
return linearGradient;
}
});
通过设置stopColors, StopHeightsStep,根据不同分段设置不同颜色,久能达到效果。如果有具体问题可以通过QQ找我。