java 多行书写,使用Java在图像上写多行文本

I looked at java.awt.Graphics documentation, stackoverflow, could not find a solution. I have in input two things, an image file and the multi line text (paragraph). I need to write the multi line text on the image file and then save it as a new image. Wondering if I am missing something really simple here.

I am open to using any good third party libraries as well.

final BufferedImage image = ImageIO.read(new File("c:/anil/Lenna.png"));

Graphics g = image.getGraphics();

g.setFont(g.getFont().deriveFont(30f));

g.drawString("Hello world", 100, 100);

g.dispose();

Above code writes just a single line on the image.

解决方案

if you want to draw several lines you have to do it explicitly...

so first step is to 'detect' lines

String str = ... //some text with line breaks;

String [] lines = str.spilt("\n"); //breaking the lines into an array

second step is to draw all lines

Graphics g = image.getGraphics();

g.setFont(g.getFont().deriveFont(30f));

int lineHeight = g.getFontMetrics().getHeight();

//here comes the iteration over all lines

for(int lineCount = 0; lineCount < lines.length; lineCount ++){ //lines from above

int xPos = 100;

int yPos = 100 + lineCount * lineHeight;

String line = lines[lineCount];

g.drawString(line, xpos, yPos);

}

g.dispose();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值