2012-01-01 87 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在您的油漆事件:但是這可能會做你想要什麼。