使用 QML 绘制 SVG

问题描述 投票:0回答:3

如何使用 qml 简单地绘制 SVG?

根据 QtDocs,可以使用以下代码绘制 SVG:

Path {
    startX: 50; startY: 50
    PathSvg { path: "L 150 50 L 100 150 z" }
}

但实际上并非如此。 那么,我该如何绘制 SVG?

qt qml
3个回答
9
投票

如果要显示路径,则必须在

Shape
中使用它:

Shape {
    ShapePath {
        fillColor: "red"
        strokeWidth: 2
        strokeColor: "blue"
        startX: 50; startY: 50
        PathSvg { path: "L 150 50 L 100 150 z" }
    }
}

4
投票

文档中没有任何关于绘图的内容。它表示使用 SVG 路径语法“定义路径”。

绘制它是一个不同的步骤:

Canvas {
    width: 400; height: 200
    contextType: "2d"

    onPaint: {
        context.strokeStyle = Qt.rgba(.4,.6,.8)
        context.path = yourPath
        context.stroke()
    }
}

请注意,只要 Qt 编译时支持 SVG,您就可以直接使用 .svg 文件作为图像源。


1
投票

为了比较,我提供了多种不同的显示方式

shape.svg

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 150">
<path fill="orange" stroke="transparent" d="M 50 50 L 150 50 L 100 150 z" />
  1. 使用
    Image
    + 文件 uri
    Image {
        source: "shape.svg"
    }
  1. 使用
    Button
    + 文件 uri
    Button {
        background: Item { }
        icon.source: "shape.svg"
        icon.width: 200
        icon.height: 150
        icon.color: "orange"
    }
  1. Shape
    +
    ShapePath
    +
    PathSvg
    :
    Shape {
        width: 200
        height: 150
        ShapePath {
            fillColor: "orange"
            strokeWidth: 0
            strokeColor: "transparent"
            startX: 50; startY: 50
            PathSvg { path: "L 150 50 L 100 150 z" }
        }
    }  
  1. Image
    + 数据 uri
    Image {
        source: `data:image/svg+xml;utf8,
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 150">
<path fill="orange" stroke="transparent" d="M 50 50 L 150 50 L 100 150 z" />
</svg>`
    }
© www.soinside.com 2019 - 2024. All rights reserved.