2012-01-01 37 views
0

在我自定义的QWidget paintEvent方法中,我想绘制一个带有圆形图像图标的圆。源图像从文件加载,然后使用QPainter组合自动转换为圆形。怎么做?谢谢!如何从图像文件创建圆形图标?

void DotGraphView::paintNodes(QPainter & painter) 
{ 
    painter.setPen(Qt::blue); 
    painter.drawEllipse(x, y, 36, 36); 
    QPixmap icon("./image.png"); 
    QImage fixedImage(64, 64, QImage::Format_ARGB32_Premultiplied); 
    QPainter imgPainter(&fixedImage); 
    imgPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); 
    imgPainter.drawPixmap(0, 0, 64, 64, icon); 
    imgPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); 
    imgPainter.setBrush(Qt::transparent); 
    imgPainter.drawEllipse(32, 32, 30, 30); 
    imgPainter.end(); 
    painter.drawPixmap(x, y, 64, 64, QPixmap::fromImage(fixedImage)); 
} 

上述代码不起作用。输出显示不是圆形图像。

+1

请详细说明它是如何工作的。它是否编译?它可以运行吗?它会产生错误的输出吗?以何种方式? – 2012-01-01 14:40:58

+0

输出显示不是圆形图像。 – allenchen 2012-01-01 14:47:14

+0

究竟是什么?你可以上传截图吗? – Cydonia7 2012-01-01 14:56:14

回答

0

你可以做到这一点相对简单,配有剪切路径:

QPainter painter(this); 
painter.setPen(Qt::blue); 
painter.drawEllipse(30, 30, 36, 36); 
QPixmap icon("./image.png"); 

QImage fixedImage(64, 64, QImage::Format_ARGB32_Premultiplied); 
fixedImage.fill(0); // Make sure you don't have garbage in there 

QPainter imgPainter(&fixedImage); 
QPainterPath clip; 
clip.addEllipse(32, 32, 30, 30); // this is the shape we want to clip to 
imgPainter.setClipPath(clip); 
imgPainter.drawPixmap(0, 0, 64, 64, icon); 
imgPainter.end(); 

painter.drawPixmap(0, 0, 64, 64, QPixmap::fromImage(fixedImage)); 

(我想如果你这样做往往缓存像素图)

3

,如果我理解正确的,我不知道,要求时

#include <QtGui/QApplication> 
#include <QLabel> 
#include <QPixmap> 
#include <QBitmap> 
#include <QPainter> 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 

    // Load the source image. 
    QPixmap original(QString("/path/here.jpg")); 
    if (original.isNull()) { 
     qFatal("Failed to load."); 
     return -1; 
    } 

    // Draw the mask. 
    QBitmap mask(original.size()); 
    QPainter painter(&mask); 
    mask.fill(Qt::white); 
    painter.setBrush(Qt::black); 
    painter.drawEllipse(QPoint(mask.width()/2, mask.height()/2), 100, 100); 

    // Draw the final image. 
    original.setMask(mask); 

    // Show the result on the screen. 
    QLabel label; 
    label.setPixmap(original); 
    label.show(); 

    return a.exec(); 
} 

缓存结果在QWidget的子类和位图传送到屏幕上所需的边界RECT在您的油漆事件:但是这可能会做你想要什么。