Shader着色器的讲解,可以参考
我们使用SweepGradient实现雷达扫描效果
完整代码如下:
public class MyRadarGradientView extends View {
private Paint mPaintCircle; // 画圆用到的paint
private Paint mPaintRadar; // 扫描用到的paint
private Shader scanShader; // 扫描渲染shader
private Matrix matrix = new Matrix(); // 旋转需要的矩阵
private int mWidth, mHeight;
private int scanSpeed = 2; // 扫描速度
private int scanAngle; // 扫描旋转的角度
//五个圆
private float[] pots = {0.05f, 0.1f, 0.15f, 0.2f, 0.25f};
public MyRadarGradientView(Context context) {
this(context,null);
}
public MyRadarGradientView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//画圆的画笔
mPaintCircle = new Paint();
mPaintCircle.setStyle(Paint.Style.STROKE);//描边
mPaintCircle.setStrokeWidth(1);//宽度
mPaintCircle.setAlpha(100);//设置透明度
mPaintCircle.setAntiAlias(true);//设置抗锯齿
mPaintCircle.setColor(Color.parseColor("#B0C4ED"));//设置画圆的颜色
// 扫描用到的paint
mPaintRadar = new Paint();
mPaintRadar.setStyle(Paint.Style.FILL_AND_STROKE); // 填充
mPaintRadar.setAntiAlias(true); // 抗锯齿
post(run);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
//正方形,取宽和高中最小值
mWidth = mHeight = Math.min(mWidth,mHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < pots.length; i++) {
canvas.drawCircle(mWidth / 2, mHeight / 2, mWidth * pots[i], mPaintCircle);
}
scanShader = new SweepGradient(mWidth / 2, mHeight / 2, new int[]{Color.TRANSPARENT, Color.parseColor("#84B5CA")}, null);
mPaintRadar.setShader(scanShader); // 设置着色器
canvas.concat(matrix);
canvas.drawCircle(mWidth / 2, mHeight / 2, mWidth * pots[4], mPaintRadar);
}
private Runnable run = new Runnable() {
@Override
public void run() {
scanAngle = (scanAngle + scanSpeed) % 360; // 旋转角度 对360取余
matrix.postRotate(scanSpeed, mWidth / 2, mHeight / 2); // 旋转矩阵
invalidate(); // 通知view重绘
postDelayed(run, 30); // 调用自身 重复绘制
}
};
}