如何在Java中将字体调整为像素大小?如何将像素转换为点



我需要创建给定像素大小的字体。

Java的Font类构造函数需要用点表示的字体大小。点是物理长度,而像素是数字化的。所以我需要dpi

手册中说,这个值包含在FontRenderContext.getTransform()中。

我发现,在我的情况下,缩放是一个,即像素=点。

不幸的是,创建大小为100的字体会产生更大的图像。

例如,下方的代码

    BufferedImage ans = new BufferedImage(width, height, imageType);
    Font font = new Font(fontName,fontStyle,height);
    Graphics2D g2 = ans.createGraphics();
    g2.setFont(font);
    FontMetrics fm = g2.getFontMetrics();
    FontRenderContext frc = g2.getFontRenderContext();
    System.out.println("height=" + height);
    System.out.println("frc.getTransform()=" +frc.getTransform());
    System.out.println("g2.getTransform()=" +g2.getTransform());
    System.out.println("fm.getAscent()+fm.getDescent()="+fm.getAscent()+"+"+fm.getDescent()+"="+(fm.getAscent()+fm.getDescent()));

    g2.drawString(str, 0, fm.getAscent());

给出

height=100
frc.getTransform()=AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
g2.getTransform()=AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
fm.getAscent()+fm.getDescent()=93+20=113

如何合身?

我在绘制字符串时使用了这段代码来确定字符串的像素大小。

x和y的计算将字符串集中在绘图区域中。y计算看起来很奇怪,因为y原点在左下角,而不是左上角。

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (font == null) {
        return;
    }
    Graphics2D g2d = (Graphics2D) g;
    FontRenderContext frc = g2d.getFontRenderContext();
    TextLayout layout = new TextLayout(sampleString, font, frc);
    Rectangle2D bounds = layout.getBounds();
    int width = (int) Math.round(bounds.getWidth());
    int height = (int) Math.round(bounds.getHeight());
    int x = (getWidth() - width) / 2;
    int y = height + (getHeight() - height) / 2;
    layout.draw(g2d, (float) x, (float) y);
}
// using javafx: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/text/package-summary.html 
Text text = new Text("Hello World");
Font font = Font.font("Arial", 10); // 10 is point size
text.setFont(font);
double width = text.getLayoutBounds().getWidth(); // width is pixel size

最新更新