Amount to adjust a rectangle
-
Assume that I have a selected Rectangle in image coordinates.
To draw this I do:
void SelectRect::paintEvent(QPaintEvent*) { QPainter painter(this); QPen pen(Qt::red, 1.0); QRectF rect(imageView->imageToScreen(selectRect.normalized())); painter.setPen(pen); // // If there's actually a selected area // if (!rect.isEmpty()) { painter.drawRect(rect .adjusted(0, 0, -1, -1));
Which is correct for a pen width of 1.0. If however the pen width is 3.0, what should the adjustment be (I don't think (0, 0, -3, -3) is correct)?
Thanks
D. -
It depends on what result you're looking for. The line grows equally to both sides i.e. for the same rectangle and width 3.0 it's gonna be 1 px inward and 1 px outward from the line of width 1.0. if you want an outline you'll have to further adjust by
(width-1)/2
outward , soadjusted(-1,-1,0,0)
and to grow inwardadjusted(1,1,-2,-2)
.It's a little wobbly for even and fractional widths so it's best to use odd values.
-
If the selection is e.g. (0,0,10,10), using the code above the drawn rectangle fits exactly inside the selection rectangle and encloses a rectangle (1, 1, 9, 9).
For larger pen sizes I think I would still want the drawn rectangle to fit exactly inside the selection rectangle.
If the pen width were 2.0 I would want the drawn rectangle to enclose a rectangle (2, 2, 8, 8).
If the pen size were 3.0 the enclosed rectangle should be (3, 3, 7, 7).
I'm sure there's a good algorithm to express that but I can't figure it out right now.
What's the normal convention for drawing a selection rect ? Inside the selection, or outside, or directly on top of?
Thanks
David -
Ok, so basically you want the rectangle to grow inward. Like I said the width grows both ways so you just have to shift it inward i.e.
float halfWidth = (pen.widthF() - 1.f) / 2.f;
and then instead of
painter.drawRect(rect.adjusted(0, 0, -1, -1));
you do
painter.drawRect(rect.adjusted(halfWidth , halfWidth , -halfWidth -1 , -halfWidth -1 ));
It's floating point, so like I said - you might see some wobble for some widths due to imperfect rounding.