5

I am trying to draw a transparent image using QImage but everytime it gives black background. I have a image background,on that I want to draw a circle which should be trasparent(with no background).How can I do that?

I have used this code

QImage image(size, QImage::Format_ARGB32);
    image.fill(qRgba(0,0,0,0));

// Pick an arbitrary size for the circle
const int centerX = size.width() / 2;
const int centerY = size.height() / 2;
const int radius = std::min(centerX, centerY) * 2 / 3;
const int diameter = radius * 2;

// Draw the circle!
QPainter painter(&image);
painter.setPen(Qt::yellow);
painter.drawEllipse(centerX-radius, centerY-radius, diameter, diameter);
4

1 回答 1

6

http://qt-project.org/doc/qt-4.8/qpainter.html#settings

http://qt-project.org/doc/qt-4.8/qpainter.html#setBrush

画家的画笔定义了如何填充形状。

希望有帮助。

编辑:添加了一个很棒的例子:

基本上下面发生的事情是将窗口设置为具有背景颜色(以便 alpha 值QImage是明显且可预测的)。被QImage初始化为具有小于 255 的 alpha 值的颜色。当小部件更新时(当显示在主窗口中时),图像被绘制。

小部件.cpp

#include "widget.h"
#include <QImage>
#include <QPainter>
#include <QPalette>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    init_image();

    QPalette p = this->palette();
    p.setColor(QPalette::Background, Qt::white);
    this->setPalette(p);
}

void Widget::init_image()
{
    image = new QImage(200, 200, QImage::Format_ARGB32);

    int opacity = 50;// Set this between 0 and 255
    image->fill(QColor(0,0,0,opacity));

    QPainter painter (image);
    painter.setPen(Qt::green);

    painter.drawEllipse(10, 10, 100, 100);
}

Widget::~Widget()
{

}

void Widget::paintEvent(QPaintEvent * e)
{
    QPainter painter(this);
    painter.drawImage(0,0, *image,0,0,-1,-1,Qt::AutoColor);
}

小部件.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPaintEvent>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
    void init_image();

public slots:
    void paintEvent(QPaintEvent *);
private:
    QImage * image;
};

#endif // WIDGET_H

主文件

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}
于 2013-04-09T20:07:45.707 回答