目录
1. 问题现象
使用QPainter,在QImage上绘图,能明显看到顶部有杂色,在QBitmap上则更明显,唯一在QPicture上绘图没出现该问题。
代码
void Widget::paintImage()
{
QPainter painter;
QImage qImage(100, 100, QImage::Format_ARGB32);
painter.begin(&qImage);
painter.setBrush(Qt::yellow);
painter.setPen(QPen(Qt::green, 1));
painter.drawRect(10, 10, 60, 60);
painter.drawText(10, 10, 60, 60, Qt::AlignCenter, tr("QImage"));
painter.setBrush(QColor(0, 0, 0, 100));
painter.drawRect(50, 50, 40, 40);
painter.end();
QPixmap qPixmap(100, 100);
painter.begin(&qPixmap);
painter.setPen(QPen(Qt::green, 1));
painter.setBrush(Qt::yellow);
painter.drawRect(10, 10, 60, 60);
painter.drawText(10, 10, 60, 60, Qt::AlignCenter, tr("QQPixmapImage"));
painter.setBrush(QColor(0, 0, 0, 100));
painter.drawRect(50, 50, 40, 40);
painter.end();
QBitmap qBitmap(100, 100);
painter.begin(&qBitmap);
painter.setPen(QPen(Qt::green, 1));
painter.setBrush(Qt::yellow);
painter.drawRect(10, 10, 60, 60);
painter.drawText(10, 10, 60, 60, Qt::AlignCenter, tr("QBitmap"));
painter.setBrush(QColor(0, 0, 0, 100));
painter.drawRect(50, 50, 40, 40);
painter.end();
QPicture qPicture;
painter.begin(&qPicture);
painter.setPen(QPen(Qt::green, 1));
painter.setBrush(Qt::yellow);
painter.drawRect(10, 10, 60, 60);
painter.drawText(10, 10, 60, 60, Qt::AlignCenter, tr("QPicture"));
painter.setBrush(QColor(0, 0, 0, 100));
painter.drawRect(50, 50, 40, 40);
painter.end();
painter.begin(this);
painter.drawImage(50, 20, qImage);
painter.drawPixmap(200, 20, qPixmap);
painter.drawPixmap(50, 170, qBitmap);
painter.drawPicture(200, 170, qPicture);
}
2. 问题原因
只能是推测,未证实
QImage、QPixmap、QBitmap主要作用还是文件,文件初始化时,如果没有填充背景,那初始的像素就是不确定的,即显示的杂色。
也可能是和电脑显示驱动关联,使用到显示驱动初始化的图片,驱动不兼容等导致的杂色。
3. 解决方案
在创建相关对象后,先使用fill填充背景,再绘图
void Widget::paintImage()
{
QPainter painter;
QImage qImage(100, 100, QImage::Format_ARGB32);
qImage.fill(QColor(0, 0, 0, 0));
...
QPixmap qPixmap(100, 100);
qPixmap.fill();
...
QBitmap qBitmap(100, 100);
qBitmap.fill();
...
}
效果如下