Canvas的意思就是畫布,而Paint 代表了Canvas上的畫筆
以下範列記錄幾種Canvas繪製幾何圖向的方法
canvas.drawArc (扇形)
canvas.drawCircle(圓)
canvas.drawOval(橢圓)
canvas.drawPoint(點)
canvas.drawRect(矩形)
canvas.drawRoundRect(圓角矩形)
canvas.drawLine(線)
cnavas.drawPath(路徑)
//新增一個畫筆
val p = Paint()
//寬度為3
p.strokeWidth = 3f
//顏色設定為紅色
p.color = Color.RED
//設定Style描邊
p.style = Paint.Style.STROKE
//新增bitmap
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
//新增一個畫布
val canvas = Canvas(bitmap)
//畫圓
canvas.drawCircle(240f, 240f, 150f, p)
val p = Paint()
p.strokeWidth = 2f
p.color = Color.RED
p.style = Paint.Style.STROKE
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val oval1 = RectF(100f, 100f, 400f, 400f)
canvas.drawArc(oval1, 30f, 300f, true, p)
val p = Paint()
p.strokeWidth = 10f
p.color = Color.RED
p.style = Paint.Style.STROKE
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val oval = RectF()
oval.left = 100f
oval.top = 100f
oval.right = 400f
oval.bottom = 300f
canvas.drawOval(oval, p)
val p = Paint()
p.strokeWidth = 10f
p.color = Color.RED
p.style = Paint.Style.STROKE
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawLine(60f, 40f, 200f, 400f, p)
val p = Paint()
p.strokeWidth = 5f
p.color = Color.RED
p.style = Paint.Style.STROKE
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val path = Path()
path.moveTo(200f, 200f)
path.lineTo(400f, 200f)
path.lineTo(400f, 400f)
path.close()
canvas.drawPath(path, p)
val p = Paint()
p.strokeWidth = 20f
p.color = Color.RED
p.style = Paint.Style.STROKE
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawPoint(60f, 390f, p)
canvas.drawPoints(floatArrayOf(60f, 300f, 100f, 300f, 200f, 300f), p)
val p = Paint()
p.strokeWidth = 2f
p.color = Color.RED
p.style = Paint.Style.STROKE
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val rect = RectF(100f, 100f, 400f, 400f)
canvas.drawRect(rect, p)
val p = Paint()
p.strokeWidth = 2f
p.color = Color.RED
p.style = Paint.Style.FILL
p.isAntiAlias = true
val bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val rect = RectF(100f, 50f, 300f, 500f)
canvas.drawRoundRect(rect, 20f, 20f, p)
完整程式:https://github.com/evanchen76/Canvas
到目前介紹了ShapDrawable與這篇的Canvas兩種繪圖方式,之後我們會再講用VectorDrawable繪制向量圖。
下一篇將以目前所學來練習一個動畫範例
線上課程:
Android 動畫入門到進階
Android UI 進階實戰(Material Design Component)
出版書:
Android TDD 測試驅動開發:從 UnitTest、TDD 到 DevOps 實踐