android Compose自定义绘制入门

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),//设置圆心中心坐标
                )
        }
效果

android Compose自定义绘制入门_第1张图片

绘制点
代码
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(),

                )
        }
效果

android Compose自定义绘制入门_第2张图片

绘制线
代码
@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
            )
        }
    }
}
效果

android Compose自定义绘制入门_第3张图片

绘制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线段的形式,非实心
        }
填充的效果

android Compose自定义绘制入门_第4张图片

画线的效果

android Compose自定义绘制入门_第5张图片

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),
                )
            }
        }

效果

android Compose自定义绘制入门_第6张图片

你可能感兴趣的:(android,compose,android,jetpack)