由于QtGraphicalEffects 模块,Qt 5 存在内置的官方解决方案,我很惊讶地发现没有人提供如此简单的解决方案。如果您的目标是 Qt 6.x QtGraphicalEffects 不幸被弃用,请跳到答案的第二部分,该部分提出了一个独立于 QtGraphicalEffects 的解决方案。
QtGraphicalEffects解决方案
在其他影响中OpacityMask 是用于此目的的类型。这个想法是用具有正确设置的radius 的Rectangle 来掩盖源Image。这是使用layering 的最简单示例:
Image {
id: img
property bool rounded: true
property bool adapt: true
layer.enabled: rounded
layer.effect: OpacityMask {
maskSource: Item {
width: img.width
height: img.height
Rectangle {
anchors.centerIn: parent
width: img.adapt ? img.width : Math.min(img.width, img.height)
height: img.adapt ? img.height : width
radius: Math.min(width, height)
}
}
}
}
这个最小代码对方形图像产生了很好的结果,但是
它还通过adapt 变量考虑非方形图像。通过将标志设置为false,生成的蒙版将始终为圆形,而与图像大小无关。这是可能的,因为使用了外部Item 填充源并允许真正的掩码(内部Rectangle)调整大小。 你显然可以摆脱外部Item,如果你只是瞄准一个填充源的掩码,不管它的纵横比如何。
这是一张可爱的猫咪图片,正方形格式(left),非正方形格式adapt: true(居中),最后是非正方形格式和adapt: false(对):
此解决方案的实现细节与其他nice answer 中基于着色器的答案非常相似(参见OpacityMask 的QML 源代码,可在here - SourceProxy 中找到),只需返回一个格式良好的ShaderEffectSource 来提供效果)。
无深度解决方案
如果您不想 - 或不能 - 依赖 QtGraphicalEffects 模块(好吧,实际上是在 OpacityMask.qml 的存在上),您可以使用着色器重新实现效果.除了已经提供的解决方案之外,另一种方法是使用step、smoothstep 和fwidth 函数。代码如下:
import QtQuick 2.5
Image {
id: image
property bool rounded: true
property bool adapt: true
layer.enabled: rounded
layer.effect: ShaderEffect {
property real adjustX: image.adapt ? Math.max(width / height, 1) : 1
property real adjustY: image.adapt ? Math.max(1 / (width / height), 1) : 1
fragmentShader: "
#ifdef GL_ES
precision lowp float;
#endif // GL_ES
varying highp vec2 qt_TexCoord0;
uniform highp float qt_Opacity;
uniform lowp sampler2D source;
uniform lowp float adjustX;
uniform lowp float adjustY;
void main(void) {
lowp float x, y;
x = (qt_TexCoord0.x - 0.5) * adjustX;
y = (qt_TexCoord0.y - 0.5) * adjustY;
float delta = adjustX != 1.0 ? fwidth(y) / 2.0 : fwidth(x) / 2.0;
gl_FragColor = texture2D(source, qt_TexCoord0).rgba
* step(x * x + y * y, 0.25)
* smoothstep((x * x + y * y) , 0.25 + delta, 0.25)
* qt_Opacity;
}"
}
}
与第一种方法类似,添加了rounded 和adapt 属性来控制效果的视觉外观,如上所述。