用Android的LinearGradient实现渐变背景效果

发布时间:2023-05-14

一、LinearGradient的特性和使用方法

LinearGradient可以为一个画笔Paint所使用,根据设定的开始和结束颜色,来产生一个颜色渐变的效果。而具体的变化方式,由设置的Shader对象所决定。 在使用时,我们通过LinearGradient的构造方法,可以指定其开始颜色、结束颜色和渐变方向。

/**
 * 通过LinearGradient构造方法创建一个渐变对象
 *
 * @param x0 渐变起始点x坐标
 * @param y0 渐变起始点y坐标
 * @param x1 渐变结束点x坐标
 * @param y1 渐变结束点y坐标
 * @param colors 渐变颜色的数组
 * @param positions 渐变颜色的相对位置数组,可为null
 * @param tile 渐变平铺模式
 */
public LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, TileMode tile)

其中参数意义如下:

  • x0:渐变起始点的X坐标
  • y0:渐变起始点的Y坐标
  • x1:渐变结束点的X坐标
  • y1:渐变结束点的Y坐标
  • colors:渐变颜色数组
  • positions:渐变颜色相对位置数组
  • tile:渐变平铺模式

二、通过LinearGradient实现渐变背景

为LinearLayout等布局控件添加渐变背景色,我们可以使用以下方法实现:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LinearLayout layout = findViewById(R.id.layout);
    int colorStart = ContextCompat.getColor(this, R.color.colorStart);
    int colorEnd = ContextCompat.getColor(this, R.color.colorEnd);
    GradientDrawable drawable = new GradientDrawable();
    drawable.setOrientation(GradientDrawable.Orientation.LEFT_RIGHT);
    drawable.setColors(new int[]{colorStart, colorEnd});
    layout.setBackground(drawable);
}

其中,colorStart和colorEnd分别表示渐变的起始颜色和结束颜色,我们使用setOrientation方法可以设置渐变方向,本例中为从左往右渐变。通过setColors方法设置颜色数组,GradientDrawable会根据颜色数组自动设置对应的 positions 数组。最后通过setBackground方法设置背景为GradientDrawable对象。

三、实现不同的渐变效果

对于不同的需求,我们可以通过在构造方法中设置不同的参数,来实现不同的渐变效果:

1. 圆形渐变

int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
float[] position = {0, 0.3f, 0.6f, 1.f};
Shader shader = new RadialGradient(300, 300, 200, colors, position, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
canvas.drawCircle(300, 300, 200, paint);

在创建RadialGradient对象时,参数依次代表中心点位置的X、Y坐标、半径、颜色数组和相对位置数组,最后指定平铺模式。 绘制圆形时,通过绘制一个圆形的路径(或使用canvas提供的drawCircle方法),设置用RadialGradient对象作为画笔,绘制圆形图像,即可实现圆形渐变效果。

2. 扫描渐变

int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
float[] position = {0, 0.3f, 0.6f, 1.f};
Shader shader = new SweepGradient(300, 300, colors, position);
Paint paint = new Paint();
paint.setShader(shader);
canvas.drawCircle(300, 300, 200, paint);

在创建SweepGradient对象时,参数依次代表中心点位置的X、Y坐标、颜色数组和相对位置数组。 绘制扫描渐变时,通过绘制一个圆形的路径(或使用canvas提供的drawCircle方法),设置用SweepGradient对象作为画笔,绘制圆形图像,即可实现扫描渐变效果。

3. 线性渐变

int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
float[] position = {0, 0.3f, 0.6f, 1.f};
Shader shader = new LinearGradient(0, 0, 500, 500, colors, position, Shader.TileMode.MIRROR);
Paint paint = new Paint();
paint.setShader(shader);
canvas.drawPath(path, paint);

在创建LinearGradient对象时,参数依次代表起始点的位置X、Y坐标、结束点的位置X、Y坐标、颜色数组和相对位置数组,最后指定平铺模式。 绘制线性渐变时,可以通过绘制一个路径对象,设置用LinearGradient对象作为画笔,绘制路径图像,即可实现线性渐变效果。