0

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

Aleksey Kontsevich
  • 4,671
  • 4
  • 46
  • 101

1 Answers1

1

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.

folibis
  • 12,048
  • 6
  • 54
  • 97
  • Yes, creating `QQuickImageProvider` ancestor now. – Aleksey Kontsevich Aug 02 '22 at 08:33
  • Works, however writing algorithm for a smooth connectable fill pattern was tricky. Also why this image from [QQuickImageProvider](https://doc.qt.io/qt-5/qquickimageprovider.html) is not loaded in `ctx.createPattern(image, repeater)` method - nothing shown, need to load it in an `Image { source: image }` component first? – Aleksey Kontsevich Aug 02 '22 at 11:15
  • I don't know how did you try to load that but I guess that you have to create an Image somehow first since the `createPattern` wants Image as an argument – folibis Aug 02 '22 at 13:02
  • It wants Image or its URI. I pass URI for both `createPattern()` and arbitrary `Image{}` component. And 1st does not work without the 2nd for some reason. How would I pass created image? – Aleksey Kontsevich Aug 02 '22 at 13:22
  • Thanks for `CanvasImageData`, the code `BDiagPattern` similar pattern will be different. I already implemented the same in C++ with `QQuickImageProvider`, now need to figure out why it is not loaded with `createPattern()` if it was not loaded first with an `Image{}`. – Aleksey Kontsevich Aug 02 '22 at 14:27
  • This is why it was not loaded: [loadImage(url image)](https://doc.qt.io/qt-6/qml-qtquick-canvas.html#loadImage-method). **Note:** _Only loaded images can be painted on the Canvas item._ So I did this: `Canvas { Component.onCompleted: loadImage("uri") }` – Aleksey Kontsevich Aug 02 '22 at 14:35