1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextShapeFactory {
private static final FontRenderContext FRC = new FontRenderContext(new AffineTransform(), true, true);
public static Shape of(Font font, String s) {
TextLayout textlayout = new TextLayout(s, font, FRC);
AffineTransform transform = AffineTransform.getTranslateInstance(0,textlayout.getAscent()-textlayout.getDescent());
return textlayout.getOutline(transform);
}
public static Shape of(Font font, char c) {
char[] chararray=new char[]{c};
LineMetrics lm = font.getLineMetrics(chararray, 0, 1, FRC);
return toTopLeft(font.createGlyphVector(FRC, chararray).getOutline());
}
public static Shape toTopLeft(Shape shape) {
Rectangle2D bounds = shape.getBounds2D();
return AffineTransform.getTranslateInstance(-bounds.getX(), -bounds.getY()).createTransformedShape(shape);
}
public static void main(String[] args) {
Shape shape = TextShapeFactory.of(new Font("Arial",Font.PLAIN, 50), '>'); // forme du caractère > avec une police Arial de 50
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Rectangle2D shapeBounds = shape.getBounds2D();
g.translate((int)(getWidth()-shapeBounds.getWidth())/2, (int)(getHeight()-shapeBounds.getHeight())/2);
((Graphics2D)g).draw(shape);
};
};
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} |
Partager