[英]Is it possible to get the right string size without use paintComponent(Graphics g)?
Actually I have these methods to get the width/height size of a string, both requires the command inside a paint component. 实际上,我有这些方法来获取字符串的宽度/高度,这两种方法都需要在paint组件内执行命令。 But I want to get this values inside a class constructor . 但我想在类构造函数中获取此值 。 This is possible? 这个有可能?
public int getStringWidth(Graphics g){
g2d = (Graphics2D) g;
metrics = g2d.getFontMetrics(this.font);
return metrics.stringWidth(this.string);
}
public int getStringHeight(Graphics g){
g2d = (Graphics2D) g;
metrics = g2d.getFontMetrics(this.font);
int height = (int)font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight();
return height;
}
font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight()
it's the best command that I got to precisely calculate the string height size and it needs Graphics g
too. font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight()
这是我精确计算字符串高度大小的最佳命令,它也需要Graphics g
。
You can try to create a BufferedImage with the right size and use createGraphics() on it to get an actual Graphics object that is drawable. 您可以尝试创建一个具有适当大小的BufferedImage,并在其上使用createGraphics()来获取可绘制的实际Graphics对象。
BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.createGraphics();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.