[英]java Graphics2D - generate dynamic image
I am learning Java Graphics2D and I have got an issue with generating the image. 我正在学习Java Graphics2D,并且在生成图像时遇到问题。
Please find the below code and the output image: 请找到以下代码和输出图像:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class DynamicImage {
public static void main(String[] args) {
Dimension imgDim = new Dimension(1000,1000);
BufferedImage buffImage = new BufferedImage(imgDim.width, imgDim.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = buffImage.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, imgDim.width, imgDim.height);
g2d.setColor(Color.BLACK);
BasicStroke bs = new BasicStroke(2);
g2d.setStroke(bs);
Font font = new Font("Arial", Font.PLAIN, 20);
g2d.setFont(font);
String[] alphabets = {"A","B","C","D","E","F","G","H","I","J","K"};
for(int i=0;i<alphabets.length;i++) {
g2d.drawString(alphabets[i], (50*(i)), 500);
g2d.drawLine((50*(i)), 500, (50*(i+1)), 500);
}
try {
ImageIO.write(buffImage, "png", new File("C:\\Alphabets.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
As you could notice above, Alphabets are overlapping with the line, which I don't want, In other words, I want my output as below: A____B___C___D___E___F___G___H___I___J___K___ 正如您在上面注意到的那样,字母与行重叠,这是我不希望的,换句话说,我想要的输出如下:A____B___C___D___E___F___G___H___I___J___K___
Could you please help by correcting the above code to get the required output ? 您可以通过更正上面的代码以获取所需的输出来提供帮助吗?
You will need to use the FontMetrics
class: 您将需要使用FontMetrics
类:
FontMetrics fm = g2d.getFontMetrics();
Then you will need to get the width of each character: 然后,您将需要获取每个字符的宽度:
int width = fm.stringWidth( alphabets[i] );
Then start drawing the line after the character width: 然后开始在字符宽度之后绘制线条:
g2d.drawLine((50*(i)) + width, 500, (50*(i+1)), 500);
Above logic is not tested, but I hope you get the idea. 以上逻辑未经测试,但希望您能理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.