java如何绘制文字
绘制文字的基本方法
在Java中,绘制文字通常使用Graphics或Graphics2D类。以下是一个简单的示例,展示如何在Swing组件上绘制文字:
import javax.swing.*;
import java.awt.*;
public class DrawTextExample extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.setColor(Color.BLACK);
g.drawString("Hello, World!", 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Text Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawTextExample());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
设置字体和颜色
使用Graphics.setFont()方法设置字体,参数为Font对象。Font的构造函数需要字体名称、样式和大小:
Font font = new Font("Serif", Font.ITALIC, 24);
g.setFont(font);
颜色通过Graphics.setColor()设置,参数为Color对象:

g.setColor(new Color(255, 0, 0)); // 红色
使用Graphics2D增强文字渲染
Graphics2D提供了更高级的文字渲染功能,如抗锯齿:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setFont(new Font("Arial", Font.BOLD, 24));
g2d.drawString("Smooth Text", 50, 50);
}
测量文字宽度和高度
获取文字宽度和高度有助于精确控制文字位置:

FontMetrics metrics = g.getFontMetrics();
int textWidth = metrics.stringWidth("Hello");
int textHeight = metrics.getHeight();
在BufferedImage上绘制文字
在BufferedImage上绘制文字与在Swing组件上类似:
BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Arial", Font.PLAIN, 16));
g2d.drawString("Text on Image", 20, 50);
g2d.dispose();
文字旋转和变换
Graphics2D支持文字旋转和其他几何变换:
AffineTransform transform = new AffineTransform();
transform.rotate(Math.PI / 4, 50, 50);
g2d.setTransform(transform);
g2d.drawString("Rotated Text", 50, 50);
多行文字绘制
手动处理多行文字需要按行拆分并逐行绘制:
String[] lines = "Line 1\nLine 2\nLine 3".split("\n");
int y = 50;
for (String line : lines) {
g.drawString(line, 50, y);
y += g.getFontMetrics().getHeight();
}






