![](/img/trans.png)
[英]Is it possible to draw in Java with Graphics without paintComponent?
[英]Is it possible to get the right string size without use paintComponent(Graphics g)?
实际上,我有这些方法来获取字符串的宽度/高度,这两种方法都需要在paint组件内执行命令。 但我想在类构造函数中获取此值 。 这个有可能?
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()
这是我精确计算字符串高度大小的最佳命令,它也需要Graphics g
。
您可以尝试创建一个具有适当大小的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.