git地址:
https://github.com/ananananzhuo-blog/ComposeCanvesSample
Canvas
Canvas绘制基本图像
Paint
绘制圆
代码
Canvas(modifier = Modifier.size(300.dp)) {
drawCircle(
color = Color.Red,//填充颜色
radius = 100.dp.toPx(),//设置绘制圆的半径
center = Offset(size.width / 2, size.height / 2),//设置圆心中心坐标
)
}
效果
绘制点
代码
Canvas(modifier = Modifier.size(300.dp)) {
val points = mutableListOf<Offset>()
val width = size.width.toInt()
for (i in 1 until width step 40) {
points.add(Offset(i.toFloat(), i.toFloat()))//正斜向的点
val x = width / 2 + width / 2 - i
points.add(Offset(x.toFloat(), i.toFloat()))//反斜向的点
}
drawPoints(
points = points,
pointMode = PointMode.Points,
color = Color.Red,
strokeWidth = 5.dp.toPx(),
)
}
效果
绘制线
代码
@Composable
fun canvasDrawLines() {
Box(modifier = Modifier.fillMaxSize(1f), contentAlignment = Alignment.Center) {
Canvas(modifier = Modifier.size(300.dp)) {
drawLine(
color = Color.Red,
start = Offset(0f, 0f),
end = Offset(size.width, size.height),
strokeWidth = 5f
)
}
}
}
效果
绘制path
代码
Canvas(modifier = Modifier.size(300.dp)) {
val path = Path().apply {
moveTo(0f, 0f)
lineTo(size.width, 0f)
lineTo(size.width, size.height)
lineTo(0f, size.height)
lineTo(0f, 0f)
close()
}
// drawPath(path = path, color = Color.Red, style = Fill)//画path实心的
drawPath(path = path, color = Color.Red, style = Stroke(width = 10f))//画path线段的形式,非实心
}
填充的效果
画线的效果
withTransform对绘制图形进行多个转换
本节实现对Rect进行旋转并缩放两倍的效果
代码
Canvas(modifier = Modifier.size(300.dp)) {
withTransform({
rotate(30f, Offset(size.width / 2, size.height / 2))
scale(2f, 2f)
}) {
drawRect(
Color.Red,
topLeft = Offset((300.dp.toPx() - 200) / 2, (300.dp.toPx() - 200) / 2),
size = Size(200f, 200f),
)
}
}