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

问题描述 投票:0回答:2

我需要创建以像素为单位的给定大小的字体。

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

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

[我发现在我的情况下,缩放比例为1,即像素=点。

不幸的是,创建大小为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

如何适应?

java graphics fonts awt
2个回答
1
投票

我已经使用此代码确定了绘制String时String的大小(以像素为单位。)>

x和y计算将String放在绘图区域的中心。 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);
}

0
投票
// 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
© www.soinside.com 2019 - 2024. All rights reserved.