我在学Jetpack作画画布。我知道drawIntoCanvas() -提供直接使用底层画布进行绘图的访问。这有助于在结合DrawScope的情况下重复使用替代绘图逻辑。
我想为不同的目标使用不同的样式行,例如:
Style 1: color = Color.Blue , strokeWidth = 3f,...
Style 2: color = Color.Red , strokeWidth = 4f, ... 我可以用代码B来re_use这些样式,我希望我能用代码A来re_use这些样式,我该怎么办?
码A
@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
@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
)
}
}
}发布于 2022-02-21 02:35:23
没有理由不使用drawInCanvas,您在A中调用的DrawScope应该是无状态的,并且不依赖于机器人油漆类。如果必须使用画图对象,则可以创建如下所示的扩展:
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函数即可。如果你必须使用油漆,使用这个。
https://stackoverflow.com/questions/71074565
复制相似问题