我有一个关于更改使用 drawChar 函数绘制的字符大小的问题。
我找到了一个解决方案:
setFont(Font.getFont(Font.FONT_STATIC_TEXT, Font.STYLE_BOLD, Font.SIZE_LARGE));
但是字符的大小只有 3 种可能性。
有没有办法增加尺寸?
还是不可能?
您可以使用自定义等宽字体。创建一个 PNG 文件,其中包含您可能绘制的所有字符,并使用来自http://smallandadaptive.blogspot.com.br/2008/12/custom-monospaced-font.html的以下代码:
公共类 MonospacedFont {
私有图像图像;
私有字符 firstChar;
私人 int numChars;
私人 int charWidth;
公共等宽字体(图像图像,char firstChar,int numChars){
如果(图像==空){
throw new IllegalArgumentException("image == null");
}
// 第一个可见的 Unicode 字符是 '!' (价值 33)
如果(firstChar <= 33){
throw new IllegalArgumentException("firstChar <= 33");
}
// 图像上必须至少有一个字符
如果(numChars <= 0){
throw new IllegalArgumentException("numChars <= 0");
}
this.image = 图像;
this.firstChar = firstChar;
this.numChars = numChars;
this.charWidth = image.getWidth() / this.numChars;
}
公共无效drawString(图形g,字符串文本,int x,int y){
// 存储当前图形剪辑区域以便以后恢复
int clipX = g.getClipX();
int clipY = g.getClipY();
int clipWidth = g.getClipWidth();
int clipHeight = g.getClipHeight();
char [] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
int charIndex = chars[i] - this.firstChar;
// 当前字符存在于图像上
if (charIndex >= 0 && charIndex <= this.numChars) {
g.setClip(x, y, this.charWidth, this.image.getHeight());
g.drawImage(image, x - (charIndex * this.charWidth), y, Graphics.TOP | Graphics.LEFT);
x += this.charWidth;
}
}
// 恢复初始剪辑区域
g.setClip(clipX,clipY,clipWidth,clipHeight);
}
}
这是使用此类的示例代码。
图像图像;
尝试 {
img = Image.createImage("/monospaced_3_5.PNG");
MonospacedFont mf = new MonospacedFont(img, '0', 10);
mf.drawString(g, "9876543210", 40, 40);
} 捕捉(IOException e){
e.printStackTrace();
}