用Compose來宣告處理圖形有幾個有優點:
- 使用Compose 的圖形元素會減少使用狀態,讓程式減少去控制元件避免產生錯誤
- 可組合函式中的位置,就是繪圖物件的預設位置
- 可組合函式的圖形 API 可以有效率地建立及釋放物件 (這點很重要呀)
Canvas(modifier = Modifier.fillMaxSize()) {
}
綜合範例code練習
Canvas(modifier = Modifier.fillMaxSize()) {
val canvasWidth = size.width
val canvasHeight = size.height
drawLine(
start = Offset(x = canvasWidth, y = 0f),
end = Offset(x = 0f, y = canvasHeight),
color = Color.Blue
)
drawLine(
start = Offset(x = 0f, y = 0f),
end = Offset(x = canvasWidth, y = canvasHeight),
color = Color.Red
)
drawCircle(
color = Color.Blue,
center = Offset(x = canvasWidth / 2, y = canvasHeight / 2),
radius = size.minDimension / 4
)
val canvasSize = size
drawRect(
color = Color.Gray,
topLeft = Offset(x = canvasWidth / 3F, y = canvasHeight / 3F),
size = canvasSize / 3F
)
drawRoundRect(
color = Color.Red,
topLeft = Offset(x = canvasWidth / 3F, y = canvasHeight / 3F),
cornerRadius = CornerRadius(x = 50f, y = 50f),
size = canvasSize / 3F
)
drawArc(
color = Color(0xFFf04231),
startAngle = -90f,
sweepAngle = 180f,
useCenter = true,
size = Size(size.width * .50f, size.height * .50f),
topLeft = Offset(size.width * .25f, 0f)
)
drawOval(
color = Color.Blue,
topLeft = Offset(x = 25.dp.toPx(), y = 90.dp.toPx()),
size = Size(
width = canvasHeight - 50.dp.toPx(),
height = canvasHeight / 2 - 50.dp.toPx()
),
style = Stroke(width = 12.dp.toPx())
)
val path = Path().apply {
moveTo(0f, 0f)
quadraticBezierTo(50.dp.toPx(), 200.dp.toPx(),
300.dp.toPx(), 300.dp.toPx())
lineTo(270.dp.toPx(), 100.dp.toPx())
quadraticBezierTo(60.dp.toPx(), 80.dp.toPx(), 0f, 0f)
close()
}
drawPath(
path = path,
Color.Blue,
)
val points = mutableListOf<Offset>()
for (x in 0..size.width.toInt()) {
val y = (sin(x * (2f * PI / canvasWidth))
* (canvasHeight / 2) + (canvasHeight / 2)).toFloat()
points.add(Offset(x.toFloat(), y))
}
drawPoints(
points = points,
strokeWidth = 3f,
pointMode = PointMode.Points,
color = Color.Blue
)
顯示結果
https://www.answertopia.com/jetpack-compose/jetpack-compose-canvas-graphics-drawing-tutorial/
https://developer.android.com/jetpack/compose/graphics