【发布时间】:2012-03-06 18:00:06
【问题描述】:
谁能帮我找到一种方法在 Java (Graphics2D) 中缩放字符串/字符以完全适合给定大小的矩形(使其从内部接触矩形)?
这是我目前所拥有的:
String s = "S"; // always a single character!
Rectangle rect = getRect(); // defines the desired size and position
AffineTransform transform = new AffineTransform();
transform.setToTranslation(rect.getX(), rect.getY());
transform.scale(rect.getWidth() / (double) fm.stringWidth(s),
rect.getHeight() / (double) fm.getAscent());
FontRenderContext frc = image.getFontRenderContext();
TextLayout tl = new TextLayout(s, g2d.getFont(), frc);
Shape shape = tl.getOutline(transform);
g2d.setClip(shape);
g2d.fill(shape.getBounds());
问题我运行此代码是,虽然字符串被缩放以大致适合矩形大小,但它并不完全适合它,即。它不会从内部触及矩形边界(这是我想要它做的!)。
使用不同的字体有帮助吗?我目前正在使用等宽字体。 或者,我必须以不同的方式进行缩放吗?
感谢您的帮助!
【问题讨论】:
-
为什么不用像 Swing 这样的图形框架?
-
我只是在为 Web 应用程序绘制图像。你知道使用 Swing 的简单解决方案吗?
-
抱歉,我没有仔细阅读这个问题。我认为您将不得不调整单个字符间距以使其与框的边缘完全接触。
-
所以你是说我走对了?你知道我是否可以使用 FontMetrics(上面列表中的 fm)来做到这一点,还是有其他方法?
-
听起来像是这样做的方式。我会为每个单词或字符创建一个对象,并根据它们的大小计算间距。
标签: java transform scale graphics2d scaletransform