How can I draw an outline around any text in AWT, something similar to this picture?
Text fonts in Java are represented by instances of the java. awt. Font class. A Font object is constructed from a name, style identifier, and a point size. We can create a Font at any time, but it's meaningful only when applied to a particular component on a given display device.
Try the following:
public void paintTextWithOutline(Graphics g) {
String text = "some text";
Color outlineColor = Color.white;
Color fillColor = Color.black;
BasicStroke outlineStroke = new BasicStroke(2.0f);
if (g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
// remember original settings
Color originalColor = g2.getColor();
Stroke originalStroke = g2.getStroke();
RenderingHints originalHints = g2.getRenderingHints();
// create a glyph vector from your text
GlyphVector glyphVector = getFont().createGlyphVector(g2.getFontRenderContext(), text);
// get the shape object
Shape textShape = glyphVector.getOutline();
// activate anti aliasing for text rendering (if you want it to look nice)
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(outlineColor);
g2.setStroke(outlineStroke);
g2.draw(textShape); // draw outline
g2.setColor(fillColor);
g2.fill(textShape); // fill the shape
// reset to original settings after painting
g2.setColor(originalColor);
g2.setStroke(originalStroke);
g2.setRenderingHints(originalHints);
}
}
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