Hello,
I'm currently reading the "C++ GUI Programming with Qt 4"-book.
In chapter 5, you create a custom "icon editor", which enables you to edit each pixel of an icon. The icon is stored in a QImage (Format_ARGB32).
When there is a mousePressEvent, a pixel is painted.
{
if(event->buttons() & Qt::LeftButton) {
setImagePixel(event->pos(), true);
} else if(event->buttons() & Qt::RightButton) {
setImagePixel(event->pos(), false);
}
}
void IconEditor::mousePressEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton) {
setImagePixel(event->pos(), true);
} else if(event->buttons() & Qt::RightButton) {
setImagePixel(event->pos(), false);
}
}
To copy to clipboard, switch view to plain text mode
void IconEditor
::setImagePixel(const QPoint &pos,
bool opaque
) {
int i = pos.x() / zoom;
int j = pos.y() / zoom;
if(image.rect().contains(i, j)) {
QRgb pixelColor = image.pixel(i, j);
if(opaque) {
image.setPixel(i, j, penColor().rgba());
} else {
image.setPixel(i, j, qRgba(0, 0, 0, 0));
}
update(pixelRect(i, j));
}
}
void IconEditor::setImagePixel(const QPoint &pos, bool opaque)
{
int i = pos.x() / zoom;
int j = pos.y() / zoom;
if(image.rect().contains(i, j)) {
QRgb pixelColor = image.pixel(i, j);
if(opaque) {
image.setPixel(i, j, penColor().rgba());
} else {
image.setPixel(i, j, qRgba(0, 0, 0, 0));
}
update(pixelRect(i, j));
}
}
To copy to clipboard, switch view to plain text mode
{
for(int i = 0; i < image.width(); ++i) {
for(int j = 0; j < image.height(); ++j) {
QRect rect
= pixelRect
(i, j
);
if(!event->region().intersect(rect).isEmpty()) {
if(color.alpha() < 255)
painter.fillRect(rect, color);
painter.fillRect(rect, color);
}
}
}
}
void IconEditor::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
for(int i = 0; i < image.width(); ++i) {
for(int j = 0; j < image.height(); ++j) {
QRect rect = pixelRect(i, j);
if(!event->region().intersect(rect).isEmpty()) {
QColor color = QColor::fromRgba(image.pixel(i, j));
if(color.alpha() < 255)
painter.fillRect(rect, color);
painter.fillRect(rect, color);
}
}
}
}
To copy to clipboard, switch view to plain text mode
It works, but unfortunately very slow. Especially when the images are quite large. Then it takes some seconds to draw a pixel and it is inpossible to draw a continuous line. How is this solved in "real" image processing applications?
And sorry for my bad english.
Bookmarks