运用到的知识点有:画线、画圆、画矩形、Path路径绘制、画图、椭圆……都很简单
二:Demo的实现、
实现思路:
重写View:
在构造函数中初始化Paint画笔;
在onMeasure方法中测量屏幕宽度,设置矩形面积范围、为paint设置Shader样式;
在onDraw中绘制,原理也就是不断地改变扇形的角度,从0一直增加到360度再归零。为了显示更加逼真,就将Canvas也跟着扇形的角度旋转。在对画布进行操作时,记住要保存现场和恢复现场;
效果实现上,点击自定义View,对Handler发送一个小小,让它一直更新扇形的角度,调用直接在线程中调用postInvalidate()方法刷新View.
public class MyCanvasView extends View { private static final int MSG_RUN = 1; private Paint mCirclePaint; private Paint mArcPaint; private Paint mLinePaint; private RectF mRectF; private int mSweepAngle; public MyCanvasView(Context context, AttributeSet attrs) { super(context, attrs); mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(Color.BLACK); mCirclePaint.setStyle(Style.STROKE); mCirclePaint.setStrokeWidth(1.f); mArcPaint.setColor(Color.GRAY); mArcPaint.setStyle(Style.FILL); mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mLinePaint.setColor(Color.BLACK); mLinePaint.setStrokeWidth(1.f); mRectF = new RectF(); Log.i("hq"," 构造函数中 mSweepAngle:"+mSweepAngle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = getMeasuredWidth(); setMeasuredDimension(size, size); mRectF.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); mArcPaint.setShader(new SweepGradient(size/2, size/2, Color.GRAY, Color.BLACK)); } @Override protected void onDraw(Canvas canvas) { int centerX = getMeasuredWidth() / 2; int centerY = getMeasuredHeight() / 2; canvas.save(); canvas.rotate(mSweepAngle, centerX, centerY); canvas.drawArc(mRectF, 0, mSweepAngle, true, mArcPaint); canvas.restore(); Log.i("hq", "mSweepAngle:" + mSweepAngle); canvas.drawLine(0, centerY, getMeasuredWidth(), centerY, mLinePaint); canvas.drawLine(centerX, 0, centerX, getMeasuredHeight(), mLinePaint); canvas.drawCircle(centerX, centerY, centerX / 2, mCirclePaint); canvas.drawCircle(centerX, centerY, centerX, mCirclePaint); } public void start() { mHandler.sendEmptyMessage(MSG_RUN); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { if(msg.what == MSG_RUN) { mSweepAngle+=2; if(mSweepAngle > 360) mSweepAngle = 0; postInvalidate(); sendEmptyMessage(MSG_RUN); } } }; }