PDA

View Full Version : DrawRect and change color of pixels in all directions



mythili
24th May 2013, 06:05
Hi,
I am going to change the color of pixels when its white by dragging the mouse from one point to another. I am drawing a rectangle over the startp point and endpoint i.e., drawRect and checking the each pixel color. In mouseMove I am able to draw the rect in all directions but I am not able to highlight the pixels in all directions. This is done only from TopLeft to BottomRight. I need this same in all directions. Please help me. Here is my code.

QPoint hili_start_point,hili_end_point;
int hili_start_x,hili_start_y,hili_end_x,hili_end_y;
QRect hiliselectionRect;

void writingArea::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setPen(QPen(QBrush(QColor(0,0,0,180)),1,Qt ::DashLine));
painter.setBrush(QBrush(QColor(255,255,0,180)));
painter.drawRect(hiliselectionRect);
}


void writingArea::mousePressEvent(QMouseEvent *event)
{
hili_start_point = event->pos();
hili_start_x = hili_start_point.x();
hili_start_y = hili_start_point.y();
hiliselectionRect.setTopLeft(event->pos());
hiliselectionRect.setBottomRight(event->pos());
}

void writingArea::mouseMoveEvent(QMouseEvent *event)
{
hiliselectionRect.setBottomRight(event->pos());
update();
}

void writingArea::mouseReleaseEvent(QMouseEvent *event)
{
hili_end_point = event->pos();
hili_end_x = hili_end_point.x();
hili_end_y = hili_end_point.y();

QRgb col;
QRect draw_rect(hili_start_x,hili_start_y,hili_end_x - hili_start_x,hili_end_y-hili_start_y);

QPixmap high_pixmap(draw_rect.size());
QImage high_image = image.copy(draw_rect);
QPainter high_painter(&image);
int width = draw_rect.width();
int height = draw_rect.height();
for (int i = hili_start_x; i < width + hili_start_x; ++i)
{
for (int j = hili_start_y; j < height + hili_start_y; ++j)
{
col = image.pixel(i, j);
QColor tempColor(col);
if (tempColor == Qt::white)
{
image.setPixel(i, j, qRgb(255,255,0));
}
}
}
int rad = (myPenWidth / 2) + 2;
update(draw_rect.normalized().adjusted(-rad, -rad, +rad, +rad));
}

Santosh Reddy
24th May 2013, 07:07
This should help


void writingArea::mouseReleaseEvent(QMouseEvent *event)
{
...
int x1 = qMin(hili_start_x, hili_end_x);
int x2 = qMax(hili_start_x, hili_end_x);

int y1 = qMin(hili_start_y, hili_end_y);
int y2 = qMax(hili_start_y, hili_end_y);

hili_start_x = x1;
hili_end_x = x2;

hili_start_y = y1;
hili_end_y = y2;

QRect draw_rect(hili_start_x,hili_start_y,hili_end_x - hili_start_x,hili_end_y-hili_start_y);
...
}


or one other way


void writingArea::mouseReleaseEvent(QMouseEvent *event)
{
...
QRect draw_rect(hili_start_x,hili_start_y,hili_end_x - hili_start_x,hili_end_y-hili_start_y);

draw_rect = draw_rect.normalized();

hili_start_x = draw_rect.topLeft().x();
hili_end_x = draw_rect.bottomRight().x();

hili_start_y = draw_rect.topLeft().y();
hili_end_y = draw_rect.bottomRight().y();
...
}