[英]How to fit font into pixel size in Java? How to convert pixels to points?
我需要以像素为单位创建给定大小的字体。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.