QML: Create cusom brush style based on standard Qt one

313 Views Asked by At

I need custom brush style similar to Qt.BDiagPattern but with custom line width, let's say 10 or 20 px. Is there an easy way?

onPaint: {
    var ctx = getContext("2d");
    ...
    ctx.fillStyle = ctx.createPattern(Qt.rgba(1.0, 0, 0, 0.5),
                                      Qt.BDiagPattern);
    ctx.fill();
}

enter image description here

1

There are 1 best solutions below

6
On

You probably have 2 options to create pattern - using a color and using an image. in a html5 Canvas you have another option - creating a pattern from another canvas but looks that in the QML implementation this option is missing. So the only way is create a pattern from Image. If you really like complex solutions and you want some dynamic pattern you can create an Image using QQuickImageProvider and so use this image as a pattern.

Another option is using CanvasImageData

Canvas {
    id: patternCanvas
    anchors.fill: parent
    onPaint: {
        var ctx = getContext('2d');
        var pattern = ctx.createImageData(20, 20);

        for (let i = 0; i < pattern.data.length; i ++)
        {
              pattern.data[i] = Math.random() * 255;
        }

        ctx.fillStyle = ctx.createPattern(pattern, "repeat");
        ctx.fillRect(0,0,width, height);
        ctx.stroke();
    }
}

the data is array of bytes in RGBA format, i.e. every pixel is 4 array items.