Hardly Coding
Hardly Coding

Reputation: 13

Image with rounded corners and PreserveAspectFit in Qt

I'm aware of this answer, but it doesn't work for:

fillMode: PreserveAspectFit

Such change results in solid color strips on the sides of the picture. Is there any way to make work without them?

Upvotes: 1

Views: 1419

Answers (1)

Amfasis
Amfasis

Reputation: 4178

You can use the paintedWidth and paintedHeight properties of Image (see here).

I find using OpacityMask from QtGraphicalEffects easier than the shader from the mentioned answer (not sure about performance).

import QtQuick 2.11
import QtQuick.Window 2.11
import QtGraphicalEffects 1.0

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Image {
        id: img
        anchors.fill: parent
        source: "your_non_fitting_image.png"

        fillMode: Image.PreserveAspectFit
        visible: false
    }

    Item {
        id: mask
        anchors.fill: img
        visible: false

        Rectangle {
            color: "white"
            radius: 20
            anchors.centerIn: parent
            width: img.paintedWidth
            height: img.paintedHeight
        }
    }

    OpacityMask {
        anchors.fill: img
        source: img
        maskSource: mask
    }
}

Upvotes: 2

Related Questions