【问题标题】:how can I get Font X offset width in java2D?如何在 java2D 中获取 Font X 偏移宽度?
【发布时间】:2011-01-25 03:47:59
【问题描述】:

我需要使用 java 2D 打印两个单词:“A”和“B

字体大小 = 100;

A”字体系列:Bodoni MT Poster Compressed

B”字体系列:Arial

我写了下面的代码来做到这一点:

BufferedImage image = new BufferedImage(400, 300, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
{//fill bg color
    g.setColor(new Color(255,255,255));
    g.fillRect(0, 0, image.getWidth(), image.getHeight());
}           

int FONT_SIZE=100;//set font size
{//print A
    g.setColor(new Color(0,0,0));
    g.setFont(new Font("Bodoni MT Poster Compressed", Font.PLAIN ,FONT_SIZE));      
    g.drawString("A",0,FONT_SIZE);
}
{//print B
    g.setColor(new Color(0,0,0));
    g.setFont(new Font("Arial", Font.PLAIN ,FONT_SIZE));        
    g.drawString("B",FONT_SIZE,FONT_SIZE);
}
g.dispose();

我得到结果图片:

但我需要这样(由 PhotoShop 制作):

我想g.drawString("B",FONT_SIZE,FONT_SIZE);的问题

如何获取字体 X 偏移宽度?

感谢您的帮助:)

【问题讨论】:

    标签: java java-2d


    【解决方案1】:

    完成setFont后,声明一个变量

    FontMetrics fm = g.getFontMetrics();
    int strA = fm.stringWidth("A"),
        strB = fm.stringWidth("B"),
        strH = fm.getHeight();
    

    现在你已经有了字母的所有尺寸,设置它们的位置(px是从左边缘到字母的距离,py是从顶部到字体基线的距离)

    int px = ..., py = ...
    g.drawString ("A", px, py);
    

    对于“B”也是如此。希望对您有所帮助,-M.S.

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 2015-02-14
      • 2017-07-21
      • 2017-04-09
      • 1970-01-01
      • 2022-06-13
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多