一年前,我的好同事就一直在用 HTML5 Canvas 做出很多很讚的作品,但那時我的方向不一樣,一直沒有接觸。最近則開始想要在 android 畫畫圖,除了很底層的 OpenGL ES 外,就想到 Canvas 啦。
在這邊簡單筆記 Android 上 Canvas 的使用(最偷懶的使用方式):
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView( new View(this) {
Paint mPaint = new Paint();
Path mPath = new Path();
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
// env init
int width = this.getWidth();
int height = this.getHeight();
int radius = width > height ? height/2 : width/2;
int center_x = width/2;
int center_y = height/2;
// prepare a paint
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
mPaint.setAntiAlias(true);
// draw a circle
canvas.drawCircle(center_x, center_y, radius, mPaint);
// draw a rectangle
mPaint.setColor(Color.GREEN);
canvas.drawRect(center_x - radius, center_y - radius, center_x + radius, center_y + radius, mPaint);
// draw a triangle
mPaint.setColor(Color.MAGENTA);
mPath.moveTo(center_x, center_y - radius);
mPath.lineTo(center_x - radius, center_y);
mPath.lineTo(center_x + radius, center_y);
mPath.lineTo(center_x, center_y - radius);
canvas.drawPath(mPath, mPaint);
// draw some text and rotation
mPaint.setTextSize(50);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
mPaint.setColor(Color.RED);
canvas.save();
canvas.rotate(45, center_x, center_y);
canvas.drawText( "Android Canvas" , center_x , center_y, mPaint);
canvas.restore();
mPaint.setColor(Color.BLUE);
canvas.drawText( "changyy.pixnet.net" , center_x , center_y + 70, mPaint);
}
});
}
}
沒有留言:
張貼留言