字体宽度为非英文字体

时间:2013-05-05 09:23:52

标签: java utf-8 fonts awt font-size

我正在尝试在纯白色背景上从印地语中绘制字符,并将生成的图像存储为jpeg。我需要动态调整图像大小以使其适合文本。目前,通过假设35像素的大小(字体大小已被设置为22)来固定图像高度。如何修复图像宽度?

到目前为止,我已尝试将图像宽度设置为不同文本行的最大长度的35像素。这没有奏效,保存的图像非常广泛。我在Java中使用图形类的drawString方法。

创建图像的功能:

public static void printImages_temp(List<String> list) {

        /* Function to print translations contained in list to images.
         * Steps:
         * 1. Take plain white image.
         * 2. Write English word on top.
         * 3. Take each translation and print one to each line.
         */

        String dest = tgtDir + "\\" + list.get(0) + ".jpg";  //destination file image.

        int imgWidth_max = 410;
        int imgHeight_max = 230;
        int fontSize = 22;

        Font f = new Font("SERIF", Font.BOLD, fontSize);

        //compute height and width of image.
        int img_height = list.size() * 35 + 20;
        int img_width = 0;
        int max_length = 0;
        for(int i = 0; i < list.size(); i++) {
            if(list.get(i).length() > max_length) {
                max_length = list.get(i).length();
            }
        }
        img_width = max_length * 20;

        System.out.println("New dimensions of image = " + img_width + " " + img_height);

        BufferedImage img = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, img_width, img_height);

        //image has to be written to another file.
        for(int i = 0; i < list.size(); i++) {
            g.setColor(Color.BLACK);
            g.setFont(f);
            g.drawString(list.get(i), 10, (i + 1) * 35);            
        }

        //g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
        g.dispose();

        try {
            ImageIO.write(img, "jpeg", new File(dest));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("File written successfully to " + dest);
    }

我的问题:

  1. 如果用于呈现文本的字体是通用的,我如何获得非拉丁字符的宽度?
  2. 有没有办法获得适用于所有UTF-8字符的宽度?

0 个答案:

没有答案