QML change image color
You can replace your image color using ShaderEffect.
ShaderEffect {
property variant src: yourImage
property real r: yourColor.r * yourColor.a
property real g: yourColor.g * yourColor.a
property real b: yourColor.b * yourColor.a
width: yourImage.width
height: yourImage.height
vertexShader: "
uniform highp mat4 qt_Matrix;
attribute highp vec4 qt_Vertex;
attribute highp vec2 qt_MultiTexCoord0;
varying highp vec2 coord;
void main() {
coord = qt_MultiTexCoord0;
gl_Position = qt_Matrix * qt_Vertex;
}
"
fragmentShader: "
varying highp vec2 coord;
uniform sampler2D src;
uniform lowp float r;
uniform lowp float g;
uniform lowp float b;
void main() {
lowp vec4 clr = texture2D(src, coord);
lowp float avg = (clr.r + clr.g + clr.b) / 3.;
gl_FragColor = vec4(r * avg, g * avg, b * avg, clr.a);
}
"
}
The above code turns your image into the grayscaled one and then applies your color.
In Qt 5 (from 5.2) you may use ColorOverlay
as follows:
import QtQuick 2.0
import QtGraphicalEffects 1.0
Item {
width: 300
height: 300
Image {
id: bug
source: "images/butterfly.png"
sourceSize: Qt.size(parent.width, parent.height)
smooth: true
visible: false
}
ColorOverlay {
anchors.fill: bug
source: bug
color: "#ff0000" // make image like it lays under red glass
}
}
In Qt 6 module QtGraphicalEffects
(which includes ColorOverlay
) was removed because of licensing issues.
In Qt 6.1 GraphicalEffects is now available again, as @SCP3008 commented below
You can also use Colorize
And the difference with ColorOverlay is: Colorize can really change the color of a image with HSL, it is more suitable for me. ColorOverlay is similar to what happens when a colorized glass is put on top of a grayscale image with RGBA.
import QtQuick 2.12
import QtGraphicalEffects 1.12
Item {
width: 300
height: 300
Image {
id: bug
source: "images/bug.jpg"
sourceSize: Qt.size(parent.width, parent.height)
smooth: true
visible: false
}
Colorize {
anchors.fill: bug
source: bug
hue: 0.0
saturation: 0.5
lightness: -0.2
}
}