Android ApiDemos示例解析(53):Graphics->Arcs

Canvas提供瞭drawArc來繪制圓弧。

public void drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)

oval :指定圓弧的外輪廓矩形區域。
startAngle: 圓弧起始角度,單位為度。
sweepAngle: 圓弧掃過的角度,順時針方向,單位為度。
useCenter: 如果為True時,在繪制圓弧時將圓心包括在內,通常用來繪制扇形。
paint: 繪制圓弧的畫板屬性,如顏色,是否填充等。
本例演示瞭drawArc的四種不同用法,

1. 填充圓弧但不含圓心:

[java] 
mPaints[0] = new Paint(); 
mPaints[0].setAntiAlias(true); 
mPaints[0].setStyle(Paint.Style.FILL); 
mPaints[0].setColor(0x88FF0000); 
mUseCenters[0] = false; 
mPaints[0] = new Paint();
mPaints[0].setAntiAlias(true);
mPaints[0].setStyle(Paint.Style.FILL);
mPaints[0].setColor(0x88FF0000);
mUseCenters[0] = false;
2. 填充圓弧帶圓心(扇形)

[java] 
mPaints[1] = new Paint(mPaints[0]); 
mPaints[1].setColor(0x8800FF00); 
mUseCenters[1] = true; 
mPaints[1] = new Paint(mPaints[0]);
mPaints[1].setColor(0x8800FF00);
mUseCenters[1] = true;
3. 隻繪圓周,不含圓心

[java] 
mPaints[3] = new Paint(mPaints[2]); 
mPaints[3].setColor(0x88888888); 
mUseCenters[3] = true; 
mPaints[3] = new Paint(mPaints[2]);
mPaints[3].setColor(0x88888888);
mUseCenters[3] = true;
4. 隻繪圓周,帶圓心(扇形)

[java] 
mPaints[3] = new Paint(mPaints[2]); 
mPaints[3].setColor(0x88888888); 
mUseCenters[3] = true; 
mPaints[3] = new Paint(mPaints[2]);
mPaints[3].setColor(0x88888888);
mUseCenters[3] = true;
本例的onDraw

[java] 
protected void onDraw(Canvas canvas) { 
 canvas.drawColor(Color.WHITE); 
  
 drawArcs(canvas, mBigOval, mUseCenters[mBigIndex], 
 mPaints[mBigIndex]); 
  
 for (int i = 0; i < 4; i++) { 
 drawArcs(canvas, mOvals[i], mUseCenters[i], mPaints[i]); 
 } 
  
 mSweep += SWEEP_INC; 
 if (mSweep > 360) { 
 mSweep -= 360; 
 mStart += START_INC; 
 if (mStart >= 360) { 
 mStart -= 360; 
 } 
 mBigIndex = (mBigIndex + 1) % mOvals.length; 
 } 
 invalidate(); 
 } 
protected void onDraw(Canvas canvas) {
 canvas.drawColor(Color.WHITE);
 
 drawArcs(canvas, mBigOval, mUseCenters[mBigIndex],
 mPaints[mBigIndex]);
 
 for (int i = 0; i < 4; i++) {
 drawArcs(canvas, mOvals[i], mUseCenters[i], mPaints[i]);
 }
 
 mSweep += SWEEP_INC;
 if (mSweep > 360) {
 mSweep -= 360;
 mStart += START_INC;
 if (mStart >= 360) {
 mStart -= 360;
 }
 mBigIndex = (mBigIndex + 1) % mOvals.length;
 }
 invalidate();
 }
同樣onDraw之中調用invalidate(),會再觸發onDraw,從而不停刷新顯示,startAngle, sweepAngle周而復始,形成動畫效果,最上的大圖順序顯示drawArc的這四種用法:

 

Paint.Style.STROKE 表示當前隻繪制圖形的輪廓,而Paint.Style.FILL表示填充圖形。

 

 作者:mapdigit
 

 

發佈留言