Blending colors in Qt
I found myself in need of blending two QColors
in Qt using an alpha ratio. As of the time of writing this post the Qt library does not provide this feature. However, it is fairly easy to create such a function yourself.
/**
* @brief Blend two colors.
* @param color1 One of the colors to be blended.
* @param color2 One of the colors to be blended.
* @param ratio The ratio between the colors. 0.5 will give a 50-50 blend.
* @return The blended color.
*/
static QColor blendColors(const QColor& color1, const QColor& color2, qreal ratio)
{
int r = color1.red()*(1-ratio) + color2.red()*ratio;
int g = color1.green()*(1-ratio) + color2.green()*ratio;
int b = color1.blue()*(1-ratio) + color2.blue()*ratio;
return QColor(r, g, b, 255);
}
The parameter ratio specifies the weight of the colors when blending. A ratio of 0.8
will result in a blend of 20% color1
and 80% color2
. A ratio of 0.5
will therefore be a 50-50 blend of the two colors.
Feel free to use this code for what ever you want.