Search code examples
javastringgraphicsshapesgraphics2d

Java - Convert character or string into a shape / area


I'd like to be able to convert any character or string into a shape or area, so that I can draw that character in whatever size, style, effects etc. I like.

To be more specific, I'm going to draw it using parallax so that it is only clearly defined at a certain angle (which is why I can't use html or anything of that nature). I already have the parallax set up, I just need the shape.

So in short, public Shape convert(char c){...}.

Alternatively if you can think of another way of achieving this, please let me know.


Just to give you a rough idea:

writing in clouds


Solution

  • According to a previous answer, it seems you can manage this as follows (assuming this method is defined on a subclass of JPanel):

    public Shape convert(char c) {
        Font f = getFont();
        // Optionally change font characteristics here
        // f = f.deriveFont(Font.BOLD, 70);
    
        FontRenderContext frc = getFontMetrics(f).getFontRenderContext();
        GlyphVector v = f.createGlyphVector(frc, new char[] { c });
        return v.getOutline();
    }
    

    It might be easier to declare the method to take a String argument, as you can pass a String as the second parameter to createGlyphVector() - plus this will likely be more efficient than converting each character individually if you need to do more than one.