我正在尝试使用 Graphics 对象进行自定义绘画。我想以自动换行样式绘制文本,因此我使用了在此页面某处找到的一些示例代码。
我的问题是我无法以任何方式更改字体大小。请帮助我,我附上了下面的可执行源代码。
谢谢
克里斯
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import javax.swing.JFrame;
public class JavaFontProblem extends JFrame {
public JavaFontProblem() {
setSize(new Dimension(1024, 768));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
String longtext = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.";
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Verdana", Font.PLAIN, 250));
AttributedString atString = new AttributedString(longtext);
AttributedCharacterIterator iterator = atString.getIterator();
LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, g2d
.getFontRenderContext());
measurer.setPosition(iterator.getBeginIndex());
int m_width = 500;
float x = 50, y = 50;
while (measurer.getPosition() < iterator.getEndIndex()) {
TextLayout layout = measurer.nextLayout(m_width);
y += layout.getAscent();
float dx = layout.isLeftToRight() ? 0 : m_width
- layout.getAdvance();
layout.draw(g2d, x + dx, y);
y += layout.getDescent() + layout.getLeading();
}
}
public static void main(String[] args) {
new JavaFontProblem().setVisible(true);
}
}