对android颜色渐变(Gradient )的改进

本文讨论的是android中如何实现更平滑的单色渐变效果。

一般来说,当我们想让界面上的某个区域呈现单色渐变效果,我们用drawable 来实现:

定义一个drawable ,取名叫gradlient_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
      <gradient android:startColor="@color/primary_dark"
        android:endColor="@android:color/transparent"
        android:angle="90"
        />
    </shape>
  </item>
</selector>

gradlient_background应用给LinearLayout

<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/gradlient_background"
...

但是这种渐变效果看起来会比较僵化。如果我们将颜色透明度调低,颜色减淡,也许效果会好些。

ScrimUtil介绍

其实还有一种更好的办法,就是自定义更好的颜色渐变曲线。google工程师 roman  写了一个名叫ScrimUtil的工具。

传统的渐变曲线和ScrimUtil的渐变曲线的比较如下:

他们的效果比较如下:

右边那张是ScrimUtil的效果,可以看出要柔和很多。

ScrimUtil的使用

if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
  View bottom = findViewById(R.id.view_base_bottom);
  bottom.setBackground(
    ScrimUtil.makeCubicGradientScrimDrawable(
     getResources().getColor(R.color.primary_dark), //颜色
     8, //渐变层数
     Gravity.BOTTOM)); //起始方向
}
来自:UI实验室