gpt4 book ai didi

java - 在屏幕中间绘制文本

转载 作者:行者123 更新时间:2023-12-03 23:01:46 25 4
gpt4 key购买 nike

我试图在我的 JFrame 窗口中间绘制文本,但它偏离了一点点。

这是我尝试过的:

FontMetrics fontMetrics = g.getFontMetrics(font);

// draw title
g.setColor(Color.WHITE);
g.setFont(font);
int titleLen = fontMetrics.stringWidth("Level 1 Over!");
g.drawString("Level 1 Over!", (screenWidth / 2) - (titleLen / 2), 80);

最佳答案

我发现 TextLayout 类为字符串提供了比 FontMetrics 更好的维度。

@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);
}

关于java - 在屏幕中间绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18483768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com