看到一个渐变色圆形圆环,效果不错,自己动手做一个。具体思路是继承View,重写onDraw()方法,绘制圆形边界,添加渐变。
渐变用到LinearGradient。看一下它的定义:
android.graphics.
LinearGradient.LinearGradient(
float x0,
float y0,
float x1,
float y1,
int[] colors,
float[] positions,
TileMode tile)
Create a shader that draws a linear gradient along a line.
-
Parameters:
- x0 The x-coordinate for the start of the gradient line
- y0 The y-coordinate for the start of the gradient line
- x1 The x-coordinate for the end of the gradient line
- y1 The y-coordinate for the end of the gradient line
- colors The colors to be distributed along the gradient line
- positions May be null. The relative positions [0..1] of each corresponding color in the colors array. If this is null, the the colors are distributed evenly along the gradient line.
- tile The Shader tiling mode
-
-
- 前四个参数,是渐变区域的左上右下坐标。
- 第五个参数是颜色数组。
- 第六个参数是颜色对应位置,如果为空,则颜色梯度变化。
- 最后一个参数,是结尾模式,也就是渐变结尾留白的处理方式,有填充,镜面,重复等模式。
看代码:
package com.example.ring;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
public class RotateRing extends View {
// 颜色数组,定义渐变色;
private int[] colors;
public RotateRing(Context context) {
this(context, null);
}
public RotateRing(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RotateRing(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
colors = new int[] {// 渐变色数组 7色
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00,
0xFFFF0000 };
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float radius = 210; //圆半径
int cX = getWidth() / 2; //圆心
int cY = getHeight() / 2;
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE); // 设置空心
paint.setStrokeWidth(2); // 设置圆环的宽度
LinearGradient shader = new LinearGradient(cX - radius, cY - radius, // 渐变区域,左上右下
cX + radius, cY + radius, colors, null, Shader.TileMode.REPEAT);
paint.setShader(shader);
canvas.drawCircle(cX, cY, radius, paint);// 画圆
SystemClock.sleep(500);
rotateArray(colors);
}
/**
* 改变颜色数组内颜色值位置,实现颜色转动
* @param arr 颜色数组
*/
public void rotateArray(int[] arr) {
int tmp = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = tmp;
invalidate(); //重绘
}
}
运行效果: