android 如何在构图中绘制向量?

7uzetpgm  于 11个月前  发布在  Android
关注(0)|答案(2)|浏览(96)

我有以下代码:

@Preview
@Composable
fun PreviewScreen(){
    val vector = ImageVector.Builder(
        defaultWidth = 100.dp,
        defaultHeight = 100.dp,
        viewportWidth = 10f,
        viewportHeight = 10f,
        tintBlendMode = BlendMode.SrcOver
    ).path(fill = Brush.horizontalGradient(listOf(Color.Green, Color.Blue))) {
        moveTo(1f,1f)
        lineTo(8f, 8f)
    }.build()

    val painter = rememberVectorPainter(image = vector)
    Canvas(modifier = Modifier.fillMaxSize()){
        with(painter){
            draw(painter.intrinsicSize)
        }
    }
}

字符串
我希望看到一条渐变线。但由于某种原因,什么也没画出来:


的数据
为什么我做错了什么

2mbi3lxu

2mbi3lxu1#

尝试添加更多线条。您使用fill参数,它使用渐变填充图形。渐变不起作用,因为终点设置为无穷大。设置endX,看到蓝色

val vector = ImageVector.Builder(
    defaultWidth = 100.dp,
    defaultHeight = 100.dp,
    viewportWidth = 10f,
    viewportHeight = 10f,
    tintBlendMode = BlendMode.SrcOver
).path(fill = Brush.horizontalGradient(listOf(Color.Green, Color.Blue), endX = 8f)) {
    moveTo(0f, 0f)
    lineTo(0f, 8f)
    lineTo(8f, 8f)
    lineTo(8f, 0f)
    lineTo(0f, 0f)
}.build()

val painter = rememberVectorPainter(image = vector)
Canvas(modifier = Modifier.fillMaxSize()) {
    with(painter) {
        draw(painter.intrinsicSize)
    }
}

字符串
如果你想画线,你应该像这样使用路径和SolidColor

path(stroke = SolidColor(Color.Black)) {         
    moveTo(0f, 0f)         
    lineTo(0f, 6f)         
    lineTo(6f, 6f)         
    lineTo(6f, 0f)         
    lineTo(0f, 0f)     
}

oxf4rvwz

oxf4rvwz2#

尝试以下

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

@Preview
@Composable
fun PreviewScreen() {
    Canvas(modifier = Modifier.fillMaxSize()) {
        val gradient = Brush.horizontalGradient(colors = listOf(Color.Green, Color.Blue))
        drawLine(
            brush = gradient,
            start = Offset(x = 0f, y = 0f), 
            end = Offset(x = size.width, y = size.height), 
            strokeWidth = 5.dp.toPx() 
        )
    }
}

字符串


的数据

相关问题