我写的时候:
QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Darken);
painter.fillRect(image.rect(), QColor("#0000FF"));
它将背景更改为蓝色。
我写的时候:
QPainter painter(&image);
painter.setCompositionMode(QPainter::CompositionMode_Lighten);
painter.fillRect(image.rect(), QColor("#FF0000"));
它将前景色更改为红色。
现在,我想一次更改两个。怎么样?
如果我运行这两个代码,结果将是错误的,因为它试图更改在先前代码中已更改的图像。
答案 0 :(得分:1)
我找到了答案。
void ClassName:recolor(QImage *image, const QColor &foreground, const QColor &background)
{
if (image->format() != QImage::Format_ARGB32_Premultiplied) {
// qCWarning(OkularUiDebug) << "Wrong image format! Converting...";
*image = image->convertToFormat(QImage::Format_ARGB32_Premultiplied);
}
Q_ASSERT(image->format() == QImage::Format_ARGB32_Premultiplied);
const float scaleRed = background.redF() - foreground.redF();
const float scaleGreen = background.greenF() - foreground.greenF();
const float scaleBlue = background.blueF() - foreground.blueF();
for (int y=0; y<image->height(); y++) {
QRgb *pixels = reinterpret_cast<QRgb*>(image->scanLine(y));
for (int x=0; x<image->width(); x++) {
const int lightness = qGray(pixels[x]);
pixels[x] = qRgba(scaleRed * lightness + foreground.red(),
scaleGreen * lightness + foreground.green(),
scaleBlue * lightness + foreground.blue(),
qAlpha(pixels[x]));
}
}
}
和:
QColor foreground = QColor("#FF0000");
QColor background = QColor("#0000FF");
recolor(&image, foreground, background);
它完美且快速地工作。我已经从Okular
源代码中给出了此代码:)