Now I feel like I've been looking all over the internet to find out how to add a border on a text, so I decided to ask here, since you guys always knows the answer.
So, how do I, in java, draw a border of approx 2 pixels around every letter in a string drawn on a Graphics2D element ?
Like this:
Thanks in advance.
I found one simple solution in Javaworld for drawing an outline on text in Java:
g.setColor(Color.red); g.drawString("Outline", ShiftWest(x, 1), ShiftNorth(y, 1)); g.drawString("Outline", ShiftWest(x, 1), ShiftSouth(y, 1)); g.drawString("Outline", ShiftEast(x, 1), ShiftNorth(y, 1)); g.drawString("Outline", ShiftEast(x, 1), ShiftSouth(y, 1)); g.setColor(Color.yellow); g.drawString("Outline", x, y);
Essentially, you draw the same string shifted in each direction first before you draw the string in the desired color. This works well for a one pixel outline, but does not scale well to thick outlines as there may be gaps in the corners if you repeat the shifting multiple times.
Another solution would be to use a transformation and getOutline() which is a method of the TextLayout class. An example for doing outline can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With