windows 使用QBrush绘制高分辨率像素图(高DPI)

2nc8po8w  于 2022-11-26  发布在  Windows
关注(0)|答案(2)|浏览(204)

当设备像素比设置为2x时,我试图绘制高分辨率图像(以便在4K显示器上显示)。如果我直接在绘图器上绘制像素图,效果会很好:

int pixelRatio = 2;
QPixmap myImage = ...;
auto pxm = myImage.scaled(imgDiameter * pixelRatio, imgDiameter * pixelRatio, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
pxm.setDevicePixelRatio(pixelRatio);
painter->drawPixmap(QPoint(xPos, yPos), pxm);

但是,由于我需要在不规则形状上绘制图像,所以我使用画笔:

int pixelRatio = 2;
QPixmap myImage = ...;
auto oldBrush = painter->brush();
auto pxm = myImage.scaled(imgDiameter * pixelRatio, imgDiameter * pixelRatio, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
pxm.setDevicePixelRatio(pixelRatio);
QBrush brush(pxm);
painter->setPen(Qt::NoPen);
painter->setBrush(brush);
painter->setBrushOrigin(xPos, yPos);
painter->drawEllipse(xPos, yPos, imgDiameter, imgDiameter);
painter->setBrush(oldBrush);

当画笔被填充时,它看起来不符合像素贴图的device泛指elRatio,因此形状内的像素贴图是原来的两倍大。
我做的有什么不对吗?

jv4diomz

jv4diomz1#

您首先需要在pixmap上绘制您想要,然后为pixmap设置所需设备像素比率,然后绘制此pixmap

if (pix.devicePixelRatio() == 2.0) {
        QPixmap output(pix.size());
        output.fill(Qt::transparent);
        QPainter pixPainter(&output);

        pixPainter.setBrush(pix);
        pixPainter.setPen(Qt::transparent);
        pixPainter.setRenderHint(QPainter::Antialiasing);
        QPainterPath path;
        path.add(...);
        ...
        pixPainter.drawPath(path);
        output.setDevicePixelRatio(pix.devicePixelRatio());
        painter.drawPixmap(0,0,output);
    }
dojqjjoe

dojqjjoe2#

QBrush允许设置一个变换矩阵,因此您可以使用1/device泛指elRatio的缩放因子。

QTransform trans;
auto brushRatio = 1.f / pixelRatio;
trans.scale(brushRatio, brushRatio);
brush.setTransform(trans);

对于您的代码,如下所示

int pixelRatio = 2;
QPixmap myImage = ...;
auto oldBrush = painter->brush();
auto pxm = myImage.scaled(imgDiameter * pixelRatio, imgDiameter * pixelRatio, 
Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QBrush brush(pxm);

QTransform trans;
auto brushRatio = 1.f / pixelRatio;
trans.scale(brushRatio, brushRatio);
brush.setTransform(trans);

painter->setPen(Qt::NoPen);
painter->setBrush(brush);
painter->setBrushOrigin(xPos, yPos);
painter->drawEllipse(xPos, yPos, imgDiameter, imgDiameter);
painter->setBrush(oldBrush);

相关问题