首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当我在Android组合中使用drawLine时,如何设置画风?

当我在Android组合中使用drawLine时,如何设置画风?
EN

Stack Overflow用户
提问于 2022-02-11 02:05:52
回答 1查看 518关注 0票数 0

我在学Jetpack作画画布。我知道drawIntoCanvas() -提供直接使用底层画布进行绘图的访问。这有助于在结合DrawScope的情况下重复使用替代绘图逻辑。

我想为不同的目标使用不同的样式行,例如:

代码语言:javascript
复制
Style 1:  color = Color.Blue , strokeWidth = 3f,...   
Style 2:  color = Color.Red ,  strokeWidth = 4f, ...   

我可以用代码B来re_use这些样式,我希望我能用代码A来re_use这些样式,我该怎么办?

码A

代码语言:javascript
复制
@Composable
fun setCanvas() {
    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawLine(
            start = Offset(x = 0f, y = canvasHeight),
            end = Offset(x = canvasWidth, y = 0f),
            color = Color.Blue,
            strokeWidth = 3f      
        )
    }

}

码B

代码语言:javascript
复制
@Composable
fun setCanvas() {
    val linePaint1 = Paint()
    linePaint1.isAntiAlias = true
    linePaint1.style = PaintingStyle.Stroke
    linePaint1.color = Color.Blue


    val linePaint2 = Paint()
    linePaint2.isAntiAlias = true
    linePaint2.style = PaintingStyle.Stroke
    linePaint2.color = Color.Red


    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawIntoCanvas {
            it.drawLine(
               Offset(x = 0f, y = canvasHeight),
               Offset(x = canvasWidth, y = 0f),
               linePaint1
            )

            it.drawLine(
               Offset(x = 10f, y = canvasHeight-50),
               Offset(x = canvasWidth-10, y = 10f),
               linePaint2
            )

        }

    }

}
EN

回答 1

Stack Overflow用户

发布于 2022-02-21 02:35:23

没有理由不使用drawInCanvas,您在A中调用的DrawScope应该是无状态的,并且不依赖于机器人油漆类。如果必须使用画图对象,则可以创建如下所示的扩展:

代码语言:javascript
复制
fun DrawScope.drawLine(
    start: Offset?,
    end: Offset?,
    paint: Paint,
    blendMode: BlendMode? = DefaultBlendMode
) = drawLine(
    start,
    end,
    paint.strokeWidth,
    paint.strokeCap.toStrokeCap(),
    paint.pathEffect.toComposePathEffect(),
    paint.alpha.toFloat() / 255f,
    paint.colorFilter.asComposeColorFilter(),
    blendMode
)

fun Paint.Cap.toStrokeCap() = when(this) {
    Paint.Cap.BUTT -> StrokeCap.Butt
    Paint.Cap.SQUARE -> StrokeCap.Square
    Paint.Cap.ROUND -> StrokeCap.Round
}

由于颜色只有差异,所以我鼓励您不要使用此方法,只需调用现有的drawLine函数即可。如果你必须使用油漆,使用这个。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71074565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档