Android绘制颜色渐变图形

Android 中的颜色渐变有三种类型:
a. 线性渐变:linear
b. 镜像渐变 : radial
c. 圆锥角度渐变 : sweep
实现方式:
  1. xml布局中实现:
    在drawable包中,使用shape绘制.
    drawable/test.xml
<?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android"  
           android:shape="rectangle" >  
    <gradient  
        android:angle="270"  <-从左到右为0;然后逆时针旋转,90度为从下到上,270为从上到下。->
        android:centerColor="#77333333"  <-中间颜色->
<-centerx和centery的值取0-1;表示中间点的位置,中间点为0的,则渐变的中间色的 位置在最上面;中间点为0.5的,则渐变的中间色在屏幕中间;中间点为1 的,则中间点在屏幕下部。->
        android:centerX="0.5"  
        android:centerY="0.5"  
        android:endColor="#ff666666"  //结束颜色
        android:startColor="#ff666666"  //开始颜色
        android:type="linear" /> 
  </shape>  
  1. 代码实现:(通过 Paint 的 setShader() 方法来设置这个渐变)
  • LinearGradient线性渐变
    在android平台中提供了两种重载方式来实例化该类分别为,他们的不同之处为参数中第一种方法可以用颜色数组,和位置来实现更细腻的过渡效果,比如颜色采样int[] colors数组中存放20种颜色,则渐变将会逐一处理。而第二种方法参数仅为起初颜色color0和最终颜色color1。
LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)
LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile)

使用实例如下:
LinearGradient lg=new LinearGradient(0,0,100,100,Color.RED,Color.BLUE,Shader.TileMode.MIRROR);
参数一为渐变起初点坐标x位置,参数二为y轴位置,参数三和四分辨对应渐变终点,最后参数为平铺方式,这里设置为镜像.
Gradient是基于Shader类,所以我们通过Paint的setShader方法来设置这个渐变,

Paint p=new Paint();
p.setShader(lg);
canvas.drawCicle(0,0,200,p); //参数3为画圆的半径,类型为float型。
  • RadialGradient镜像渐变
    有了上面的基础,我们一起来了解下径向渐变。和上面参数唯一不同的是,径向渐变第三个参数是半径,其他的和线性渐变
    相同。
RadialGradient(float x, float y, float radius, int[] colors, float[] positions, Shader.TileMode tile) 
RadialGradient(float x, float y, float radius, int color0, int color1, Shader.TileMode tile)
  • SweepGradient角度渐变
    对于一些3D立体效果的渐变可以尝试用角度渐变来完成一个圆锥形,相对来说比上面更简单,前两个参数为中心点,然后通过载入的颜色来平均的渐变渲染。
    SweepGradient(float cx, float cy, int[] colors, float[] positions) //对于最后一个参数SDK上的描述为May be NULL. The relative position of each corresponding color in the colors array, beginning with 0 and ending with 1.0. If the values are not monotonic, the drawing may produce unexpected results. If positions is NULL, then the colors are automatically spaced evenly.,所以Android123建议使用下面的重载方法,本方法一般为NULL即可。
SweepGradient(float cx, float cy, int color0, int color1)

猜你喜欢

转载自blog.csdn.net/m0_37780940/article/details/104791958
今日推荐