今天要來簡單提一下Canvas,他可以在你的視圖繪畫一些你要的形狀,像是線(line)、圓形(Circle)等,那麼今天就來畫一些形狀出來,並且看到Paint的功能,那麼就開始設計!
public class CanvasView extends View {
public CanvasView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//執行繪畫命令
}
}
接著先來簡介一下畫筆(Paint),Canvas比較多的是繪製圖形的方法、給予你繪製圖形的路徑等,但如果要更改無論是顏色、字體大小或是透明度等都要從Paint來設定,那麼Paint也包含了很多的方法,像是:
接著就先在onDraw新增一支畫筆(藍色、文字大小32px)。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//新增畫筆
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(32);
}
接著來使用Canvas畫不同的圖案!
//圓形&文字
canvas.drawText("圓形",320,80,paint);
//x、y、半徑
canvas.drawCircle(349,170,70,paint);
//線&文字
paint.setColor(Color.CYAN);
canvas.drawLine(80,100,80,280,paint);
canvas.drawText("線",75,80,paint);
//四邊形&文字
paint.setARGB(200,120,20,190);
canvas.drawText("四邊形",550,80,paint);
canvas.drawRect(545,100,645,200,paint);
三角形疑似沒有method去畫,可以自己用path去畫一個:
//路徑(Path)繪製三角形
paint.setColor(Color.parseColor("#FF00FF"));
canvas.drawText("三角形",50,340,paint);
Path path = new Path();
//畫筆起始位置
path.moveTo(90, 370);
//移動至路徑
path.lineTo(50, 430);
path.lineTo(130, 430);
//關閉輪廓(實心)
path.close();
canvas.drawPath(path, paint);
//環形&文字
paint.setColor(Color.parseColor("#E2B319"));
canvas.drawText("環形",340,340,paint);
canvas.drawOval(320,360,420,420,paint);
這樣子就完成了一些簡單的圖形囉,而明天會再與SurfaceView做結合,今天可能還有很多的一些繪圖沒介紹到。
如果想了解更多的:Android Developers
public class CanvasView extends View {
public CanvasView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//新增畫筆
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(32);
//圓形&文字
canvas.drawText("圓形",320,80,paint);
//x、y、半徑
canvas.drawCircle(349,170,70,paint);
//線&文字
paint.setColor(Color.CYAN);
canvas.drawLine(80,100,80,280,paint);
canvas.drawText("線",75,80,paint);
//四邊形&文字
paint.setARGB(200,120,20,190);
canvas.drawText("四邊形",550,80,paint);
canvas.drawRect(545,100,645,200,paint);
//路徑(Path)繪製三角形
paint.setColor(Color.parseColor("#FF00FF"));
canvas.drawText("三角形",50,340,paint);
Path path = new Path();
//畫筆起始位置
path.moveTo(90, 370);
//移動至路徑
path.lineTo(50, 430);
path.lineTo(130, 430);
path.close();
canvas.drawPath(path, paint);
//環形&文字
paint.setColor(Color.parseColor("#E2B319"));
canvas.drawText("環形",340,340,paint);
canvas.drawOval(320,360,420,420,paint);
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CanvasView(this));
}
}