java/swing: converting a text string to a Shape

后端 未结 3 703
悲哀的现实
悲哀的现实 2020-12-06 06:29

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?

3条回答
  •  春和景丽
    2020-12-06 06:36

    If I understood you correctly, this is not to address your exact answer, but it's a start...

    //Rough pseudo code
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics2D;
    import java.awt.TexturePaint;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    
    
    
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = (Graphics2D)image.getGraphics();
    
    //Paint with texturing brush
    Rectangle2D rect2D = new Rectangle2D.Double(0, 0, width, height);
    graphics.setPaint(new TexturePaint(image, rect2D));
    graphics.fill(rect2D);
    
    //Draw text
    graphics.drawString("my text goes here", xPos, yPos);
    

    In Summary,

    1. Create a BufferedImage object of width and height and ImageType.
    2. Get the image's Graphics object.
    3. Paint that graphics like you please (i.e. create a rectangle, circle, text, etc.)
    4. Write that image to a stream (file, ServletRequest, etc.)

提交回复
热议问题