Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thick border of drawn string

Tags:

java

string

draw

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:
Text with 2px border


Thanks in advance.

like image 954
Kristoffer Dorph Avatar asked Oct 06 '11 19:10

Kristoffer Dorph


1 Answers

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.

like image 151
Jessica Brown Avatar answered Sep 28 '22 02:09

Jessica Brown