如何从图像文件创建圆形图标

How to create circle icon from image file?

本文关键字:图标 文件创建 图像      更新时间:2023-10-16

在我自定义的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));
}

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

我不知道我是否理解正确,但这可能会做你想要的:

#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子类中,并在请求时在绘制事件中将所需的边界矩形blit到屏幕上。

您可以通过一个剪辑路径相对简单地做到这一点:

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));

(如果你经常这样做,我会缓存像素图)