使用梯度渲染/漸變渲染(SweepGradient)可以實現雷達掃描效果,它的初始角度是0,使用矩陣變換的旋轉操作可以重置SweepGradient的角度
mSweepGradient.setLocalMatrix(matrix);
matrix.setRotate(degree, mWidth / 2, mWidth / 2);
最後再使用
postInvalidate();
無限重繪。
代碼如下:
public class RadarView extends View {
private Paint mPaint;
private SweepGradient mSweepGradient;
private Matrix matrix;
//畫筆粗細
private int strokeWidth = 5;
/**
* 旋轉的角度
**/
private int degree = 0;
public RadarView(Context context) {
this(context, null);
}
public RadarView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public RadarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
mPaint.setAntiAlias(true);
matrix = new Matrix();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//將背景設置成白色
canvas.drawColor(Color.WHITE);
int mWidth = canvas.getWidth();
if(mSweepGradient == null){
mSweepGradient = new SweepGradient(mWidth / 2, mWidth / 2, new int[]{Color.TRANSPARENT, Color.CYAN}, null);
}
//畫圓1
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(strokeWidth);
mPaint.setColor(Color.parseColor("#e04095af"));
canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 2, mPaint);
//畫圓2
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(strokeWidth);
mPaint.setColor(Color.parseColor("#e04095af"));
canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 8 * 3, mPaint);
//畫圓3
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(strokeWidth);
mPaint.setColor(Color.parseColor("#e04095af"));
canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 4, mPaint);
//畫圓4
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(strokeWidth);
mPaint.setColor(Color.parseColor("#e04095af"));
canvas.drawCircle(mWidth / 2, mWidth / 2, (mWidth-strokeWidth) / 8, mPaint);
//畫點
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(strokeWidth);
canvas.drawPoint(mWidth / 2, mWidth / 2, mPaint);
//通過梯度渲染畫掃描框
mPaint.setStyle(Paint.Style.FILL);
mPaint.setShader(mSweepGradient);
canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2, mPaint);
//下面開始爲重繪之前做準備
//(1)重繪之前,將mPaint還原成初始狀態
mPaint.reset();
//(2)使用Matrix旋轉
mSweepGradient.setLocalMatrix(matrix);
matrix.setRotate(degree, mWidth / 2, mWidth / 2);
degree++;
if (degree > 360) {
degree = 0;
}
postInvalidate();
}
}
效果如下:
另外,該demo沒有使用自定義屬性做擴展, 如果需要用到自定義屬性的話請看我的另一篇文章