我正在学习Java Graphics2D,我遇到了生成图像的问题。
请找到以下代码和输出图像:
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();
}
}
}
正如您在上面注意到的那样,Alphabets与行重叠,我不想要,换句话说,我想要我的输出如下: 甲____乙___Ç___ d ___Ë___˚F___ģ___ħ___我___Ĵ___ķ___
您可以通过更正上述代码来获得所需的输出吗?
答案 0 :(得分:2)
您需要使用FontMetrics
类:
FontMetrics fm = g2d.getFontMetrics();
然后你需要得到每个角色的宽度:
int width = fm.stringWidth( alphabets[i] );
然后开始在字符宽度后绘制线条:
g2d.drawLine((50*(i)) + width, 500, (50*(i+1)), 500);
以上逻辑没有经过测试,但我希望你明白这一点。