誰かが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());
私がこのコードを実行している問題は、文字列が長方形のサイズにほぼ合うようにスケーリングされているにもかかわらず、正確に合わないことです。内側から長方形の境界に触れません(これが私が望んでいることです!)。
別のフォントを使用するのに役立ちますか?現在、等幅フォントを使用しています。または、スケーリングを別の方法で行う必要がありますか?
ご協力いただきありがとうございます!