Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java/swing: converting a text string to a Shape

I want to convert some arbitrary text to a Shape (java.awt.Shape) and then stroke/fill the Shape to draw it. How can I do this?

like image 994
Jason S Avatar asked Mar 17 '10 22:03

Jason S


2 Answers

Hm I did not know the answer to this but after a bit tweaking and poking around in with Eclipse content assist i found this which seems to be what you need:

EDIT: i changed to code to change the way the string is displayed which is the reason you asked what you asked :) Try it. It renders the string with red color and a dashed outline

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.GlyphVector;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JPanel{

    private Shape s;

    public Test() {
        Font f = getFont().deriveFont(Font.BOLD, 70);
        GlyphVector v = f.createGlyphVector(getFontMetrics(f).getFontRenderContext(), "Hello");
        s = v.getOutline();
        setPreferredSize(new Dimension(300,300));
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.translate(100, 150);
        g2.rotate(0.4);
        g2.setPaint(Color.red);
        g2.fill(s);
    g2.setPaint(Color.black);
        g2.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1, new float[]{1,0.4f,1.5f}, 0));
        g2.draw(s);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Test");
        Component c = new Test();
        f.getContentPane().add(c);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}

Also note that you can get the individual characters from the string by calling:

getGlyphOutline(glyphIndex)
like image 70
Savvas Dalkitsis Avatar answered Oct 15 '22 02:10

Savvas Dalkitsis


Use the TextLayout class (see the getOutline() method). Theres an example here

like image 33
objects Avatar answered Oct 15 '22 01:10

objects