Java / Swing: convert text string to shape
•
Java
I want to convert some arbitrary text into shape (Java. AWT. Shape), and then stroke / fill the shape What shall I do?
Solution
Well, I don't know the answer, but after a little adjustment and stamping, with the help of eclipse content, I find that this seems to be what you need:
Editor: I changed the code to change the way the string is displayed. Why did you ask what you asked:) try it It presents a string of red and dashed lines
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 each character in the string by calling the following string:
getGlyphOutline(glyphIndex)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码