How to Change Font Size in drawString Java

前端 未结 6 1703
清歌不尽
清歌不尽 2021-02-02 07:33

How to make the font size bigger in g.drawString(\"Hello World\",10,10); ?

6条回答
  •  滥情空心
    2021-02-02 07:50

    I've an image located at here, Using below code. I am able to contgrol any things on the text that i wanted to write (Eg,signature,Transparent Water mark, Text with differnt Font and size).

     import java.awt.Font;
        import java.awt.Graphics2D;
        import java.awt.Point;
        import java.awt.font.TextAttribute;
        import java.awt.image.BufferedImage;
        import java.io.ByteArrayOutputStream;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.net.URL;
        import java.util.HashMap;
        import java.util.Map;
    
        import javax.imageio.ImageIO;
    
        public class ImagingTest {
    
            public static void main(String[] args) throws IOException {
                String url = "http://images.all-free-download.com/images/graphiclarge/bay_beach_coast_coastline_landscape_nature_nobody_601234.jpg";
                String text = "I am appending This text!";
                byte[] b = mergeImageAndText(url, text, new Point(100, 100));
                FileOutputStream fos = new FileOutputStream("so2.png");
                fos.write(b);
                fos.close();
            }
    
            public static byte[] mergeImageAndText(String imageFilePath,
                    String text, Point textPosition) throws IOException {
                BufferedImage im = ImageIO.read(new URL(imageFilePath));
                Graphics2D g2 = im.createGraphics();
                Font currentFont = g2.getFont();
                Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
                g2.setFont(newFont);
    
    
                Map attributes = new HashMap<>();
    
                attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
                attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
                attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 2.8));
                newFont = Font.getFont(attributes);
    
                g2.setFont(newFont);
                g2.drawString(text, textPosition.x, textPosition.y);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(im, "png", baos);
                return baos.toByteArray();
            }
        }
    

提交回复
热议问题