关于ShapeDrawable应用的一些介绍(中)之Gradient

Gradient,渐变,是在界面设计中最经常用到的一种技巧,只要涉及到颜色的处理,浓妆淡抹总相宜,说的就是它。

Android中,当然也提供了这样的技能,就看我们能不能 get it了?人比较笨,还是得从基础学习,再慢慢来熟悉它。

我们在 res / drawable/ 中 创建一个xml,代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:shape="rectangle">  
  4.     <corners android:radius="15dip"/>  
  5.     <solid android:color="#0000FF"/>  
  6.     <gradient android:startColor="#FF0000"  
  7.         android:endColor="#00FF00"  
  8.         android:type="linear"/>  
  9. </shape>  


由上面的代码,我们可以看到定义了圆角,实心填充蓝色和从红到绿的线性渐变,默认的渐变是从左到右的,可以通过下面的一个属性来改变渐变的方向:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:shape="rectangle">  
  4.     <corners android:radius="15dip"/>  
  5.     <gradient android:startColor="#FF0000"  
  6.         android:endColor="#00FF00"  
  7.         android:angle="90"  
  8.         android:type="linear"/>  
  9. </shape>  

为了方便地来对比看一下各种颜色的变换,我们定义了几个不同的渐变颜色来看看效果,如下:


可以看到,从0到360,这个渐变的颜色会慢慢随着逆时针的方向来从水平变成垂直再变成水平。而这个角度的值必须是45的倍数,否则会出报错的。不过我们仔细看一下,好像45度跟0度也没啥不同,135度也好像就是从右到左而已,还不清楚为什么。

目前的渐变只是两种颜色的渐变,而Android还提供了一种中间的颜色的过渡,如下:

  1. <gradient android:startColor="#FF0000"  
  2.     android:centerColor="#0000FF"  
  3.     android:centerY="0.1"  
  4.     android:endColor="#00FF00"  
  5.     android:angle="90"  
  6.     android:type="linear"/>  

android:centerColor 就提供了这样的功能,另外centerX/Y则可以改变这个中间的颜色相对的位置(当然,X就只对左右的渐变有用,而Y只对上下的渐变有用),效果如下:


centerX/Y的值只能是从0到1.0的,从开始颜色开始(是开始颜色,如果我们的angle变成180,即从右到坐,0.1的值,还是从红色开始的,可以简单地认为红色就变成只有0.1了)

上面我们看到的都是线性的,而Android中关于gradient,提供了另外两种:radial 和 sweep。

1)Radial

关于Radial的,我们可以有如下定义:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:shape="oval">  
  4.     <corners android:radius="15dip"/>  
  5.     <gradient android:startColor="#FF0000"  
  6.         android:endColor="#00FF00"  
  7.         android:gradientRadius="100"  
  8.         android:type="radial"/>  
  9. </shape>  

这里有一点要注意,当android:type="raidal"的时候,gradientRadius的属性是一定要设置的,它设置了这个放射的半径,具体我们来看看效果吧


2)Sweep

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:shape="rectangle">  
  4.     <corners android:radius="15dip"/>  
  5.     <gradient android:startColor="#FF0000"  
  6.         android:centerColor="#0000FF"  
  7.         android:centerX="0.1"  
  8.         android:endColor="#00FF00"  
  9.         android:type="sweep"/>  
  10. </shape>  

在type="sweep"中,angle的属性是一点用没有的,而centerX/Y跟radial一样,都是针对开始颜色的比例来设置的,x是针对开始颜色在X轴上面的比例,而y则是针对在Y轴上面的比例,具体看下面效果图:


在于Gradient的基础属性,我们常用的大概也就那么多了,晚上就先到这吧,下次再继续。

大家如果有兴趣,也可以看一下前面的一篇文章:

关于ShapeDrawable应用的一些介绍(上)

原文地址:https://www.cnblogs.com/yaowen/p/5435468.html