I have the following code:
private _x,_y,_w,_h;
protected void paintComponent( Graphics g_ ) {
g_.setStroke( new BasicStroke(2) );
g_.drawLine(_x, _y, _x+_w, _y+_h);
g_.drawLine(_x, _y+_h, _x+_w, _y);
}
In my case I'm drawing the diagonals of a square so: _w==_h
.
My problem the two line don't have the same apparent thikness: the first line look thicker than the second. When checking the actual pixels drawn here's the difference of rendering:
I don't really care which one should be considered "correct" (though I'd like to understand the reasons of this result), but I'd like some coherence here, that both lines have the same rendering: how can I do that?
(when I use a 1px stroke, there's no difference between the two lines).
Followup to Olavi's ansewer:
Using an odd number of pixel for the stroke doesn't solve the problem:
Enabling anti-aliasing leads to another problem: the stroke of the square in which the cross is drawn gets blurred:
Basically you have two options:
Personally I prefer antialiasing, because it's pretty and I like pretty things. However to explain why a stroke width of 2 behaves like that: Java does not know whether or not draw the line with the first way or the second way (I can't really explain exactly why it does what it does, but this is what I see). To further elaborate this answer, try starting the other line one pixel to the left or to the right: this should result in two lines with the same thickness.
To use antialiasing, do the following (untested code!). Code picked up from here:
Graphics2D graphics2D = (Graphics2D) g_;
graphics2D.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawLine(_x, _y, _x+_w, _y+_h);
graphics2D.drawLine(_x, _y+_h, _x+_w, _y);