Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to draw Transparent qimage that includes drawing of a circle using Qt

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);
like image 366
Rujuta Raval Avatar asked Apr 09 '13 17:04

Rujuta Raval


1 Answers

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

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

The painter's brush defines how shapes are filled.

Hope that helps.

EDIT: Added an awesome example:

Basically what happens below, is the window is set to have a background color (so that the alpha value of the QImage is noticeable and predicable). The QImage is initialized to have a color with an alpha value less than 255. The image gets painted when the widget updates (when shown in the main).

widget.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);
}

Widget.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

Main.cpp

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

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

    return a.exec();
}
like image 191
phyatt Avatar answered Sep 21 '22 08:09

phyatt