/*
* 利用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, 0, dst, 0, src.length>>1);
//在画布上应用变换的矩阵
canvas.concat(mMatrix);
//绘制图形
mPaint.setColor(Color.GRAY);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(0, 0, 64, 64, mPaint);
canvas.drawLine(0, 0, 64, 64, mPaint);
canvas.drawLine(64, 0, 0, 64, mPaint);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL);
float x=64/2;
//让字体的中心与图形的中心重合
float y=64/2-(mFontMetrics.ascent+mFontMetrics.descent)/2;
canvas.drawText(src.length/2+"", x, y, mPaint);
canvas.restore();
}
public SampleView(Context context) {
super(context);
mPaint.setStrokeWidth(4);
mPaint.setTextSize(40);
mPaint.setTextAlign(Paint.Align.CENTER);
mFontMetrics=mPaint.getFontMetrics();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.save();
canvas.translate(10, 10);
//移动一个点,实现平移变换,将左上顶点从0,0移到5,5其它点相对位置不变,实现按对角线方向的平移
doDraw(canvas, new float[]{0, 0}, new float[]{5, 5});
canvas.restore();
canvas.save();
canvas.translate(160, 10);
//移动两个点,实现旋转变换,以圆点为圆心旋转45度
doDraw(canvas, new float[]{32,32,64,32},
new float[]{32,32,64,48});
canvas.restore();
canvas.save();
canvas.translate(10, 110);
//移动三个点,实现旋转/剪切变换
doDraw(canvas, new float[]{0, 0, 64, 0, 0, 64 },
new float[]{ 0, 0, 96, 0, 24, 64});
canvas.restore();
canvas.save();
canvas.translate(160, 110);
//移动四个点,实现透视变换
doDraw(canvas, new float[]{ 0, 0, 64, 0, 64, 64, 0, 64 },
new float[]{ 0, 0, 96, 0, 64, 96, 0, 64});
canvas.restore();
}
}
}
Android Api Demos登顶之路(八十四)Graphics-->PolyToPoly
最新推荐文章于 2024-03-11 20:01:07 发布