I need to draw white text with black outline on a Graphics object I get from an image. I first draw the same text 4 times (moved left or right by one pixel) with black color and then once with white color. However this won't work well if outline needs to be more than 1px wide, and really seems like a hack. Is there a better way to do this?
final BufferedImage image = ImageIO.read(new File("./test.jpg"));
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(45F));
// coordinates
int x = 100;
int y = 100;
String text = "Hello world";
g.setColor(Color.black);
g.drawString(text, x + 1, y - 1);
g.drawString(text, x + 1, y + 1);
g.drawString(text, x - 1, y - 1);
g.drawString(text, x - 1, y + 1);
g.setColor(Color.white);
g.drawString(text, x, y);
screenshot: https://i.sstatic.net/TCOPr.png
The other option is to use below piece of code of creating a shape and then first drawing outline and then fill it:
        Graphics2D g2d = (Graphics2D)g;
        AffineTransform transform = g2d.getTransform();
        transform.translate(x, y);
        g2d.transform(transform);
        g2d.setColor(Color.black);
        FontRenderContext frc = g2d.getFontRenderContext();
        TextLayout tl = new TextLayout(text, g.getFont().deriveFont(45F), frc);
        Shape shape = tl.getOutline(null);
        g2d.setStroke(new BasicStroke(5f));
        g2d.draw(shape);
        g2d.setColor(Color.white);
        g2d.fill(shape);
Output:

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