修改字符大小字体

时间:2012-06-07 13:48:29

标签: java-me midp lcdui

我有一个关于更改用drawChar函数绘制的字符大小的问题。

我找到了一个解决方案:

setFont(Font.getFont(Font.FONT_STATIC_TEXT, Font.STYLE_BOLD, Font.SIZE_LARGE));

但是角色的大小只有3种可能性 有没有办法增加尺寸?
或者这是不可能的?

1 个答案:

答案 0 :(得分:0)

您可以使用自定义等宽字体。创建一个PNG文件,其中包含您可能绘制的所有字符,并使用http://smallandadaptive.blogspot.com.br/2008/12/custom-monospaced-font.html下的代码


    public class MonospacedFont {

    private Image image;
    private char firstChar;
    private int numChars;
    private int charWidth;

    public MonospacedFont(Image image, char firstChar, int numChars) {
        if (image == null) {
            throw new IllegalArgumentException("image == null");
        }
        // the first visible Unicode character is '!' (value 33)
        if (firstChar <= 33) {
            throw new IllegalArgumentException("firstChar <= 33");
        }
        // there must be at lease one character on the image
        if (numChars <= 0) {
            throw new IllegalArgumentException("numChars <= 0");
        }
        this.image = image;
        this.firstChar = firstChar;
        this.numChars = numChars;
        this.charWidth = image.getWidth() / this.numChars;
    }

    public void drawString (Graphics g, String text, int x, int y) {
        // store current Graphics clip area to restore later
        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;
            // current char exists on the image
            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;
            }
        }

        // restore initial clip area
        g.setClip(clipX, clipY, clipWidth, clipHeight);
    }
    }

以下是使用此类的示例代码。


    Image img;
    try {
        img = Image.createImage("/monospaced_3_5.PNG");
        MonospacedFont mf = new MonospacedFont(img, '0', 10);
        mf.drawString(g, "9876543210", 40, 40);
    } catch (IOException e) {
        e.printStackTrace();
    }