Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw an outline around text in AWT?

Tags:

java

awt

How can I draw an outline around any text in AWT, something similar to this picture?

Outline

like image 386
Konrad Garus Avatar asked Apr 04 '12 17:04

Konrad Garus


People also ask

What is AWT font in Java?

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.


1 Answers

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);
    }
}
like image 145
Eddo Avatar answered Nov 05 '22 19:11

Eddo