/*
* 利用Matrix 類可以實作圖像的平衡、旋轉、綻放等。一種方法是通過指定Matrix的值來實作。
* 另一種方法是通過Matrix的
* setPolyToPoly(float[] src, int srcIndex, float[] dst, int dstIndex, int pointCount)
* 方法。通過指定某點在變化前和變化後的位置,(其它點保持相對位置不變),系統自動計算實作該變化的
* Matrix.
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private class SampleView extends View{
private Paint mPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
private Matrix mMatrix=new Matrix();
private Paint.FontMetrics mFontMetrics;
private void doDraw(Canvas canvas,float[] src,float[] dst){
//儲存畫布的狀态
canvas.save();
//設定矩陣的變換方式
mMatrix.setPolyToPoly(src, , dst, , src.length>>);
//在畫布上應用變換的矩陣
canvas.concat(mMatrix);
//繪制圖形
mPaint.setColor(Color.GRAY);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(, , , , mPaint);
canvas.drawLine(, , , , mPaint);
canvas.drawLine(, , , , mPaint);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL);
float x=/;
//讓字型的中心與圖形的中心重合
float y=/-(mFontMetrics.ascent+mFontMetrics.descent)/;
canvas.drawText(src.length/+"", x, y, mPaint);
canvas.restore();
}
public SampleView(Context context) {
super(context);
mPaint.setStrokeWidth();
mPaint.setTextSize();
mPaint.setTextAlign(Paint.Align.CENTER);
mFontMetrics=mPaint.getFontMetrics();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.save();
canvas.translate(, );
//移動一個點,實作平移變換,将左上頂點從0,0移到5,5其它點相對位置不變,實作按對角線方向的平移
doDraw(canvas, new float[]{, }, new float[]{, });
canvas.restore();
canvas.save();
canvas.translate(, );
//移動兩個點,實作旋轉變換,以圓點為圓心旋轉45度
doDraw(canvas, new float[]{,,,},
new float[]{,,,});
canvas.restore();
canvas.save();
canvas.translate(, );
//移動三個點,實作旋轉/剪切變換
doDraw(canvas, new float[]{, , , , , },
new float[]{ , , , , , });
canvas.restore();
canvas.save();
canvas.translate(, );
//移動四個點,實作透視變換
doDraw(canvas, new float[]{ , , , , , , , },
new float[]{ , , , , , , , });
canvas.restore();
}
}
}