java - Swing 中带有小字体的字符串的边界

标签 java swing fonts

关于计算应该绘制到 Swing 组件中的字符串的大小(宽度或高度)有很多(很多)问题。并且有许多建议的解决方案。但是,我注意到大多数这些解决方案不能适用于小字体。

下面是一个MCVE展示了一些方法:

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.util.function.BiFunction;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TextBoundsTest
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Font baseFont = new Font("Sans Serif", Font.PLAIN, 10);
        Font smallFont0 = baseFont.deriveFont(0.5f);
        Font smallFont1 = baseFont.deriveFont(0.4f);

        f.getContentPane().setLayout(new GridLayout(5,2));

        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont0, 
                TextBoundsTest::computeBoundsWithFontMetrics, 
                "FontMetrics"));
        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont1, 
                TextBoundsTest::computeBoundsWithFontMetrics, 
                "FontMetrics"));

        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont0, 
                TextBoundsTest::computeBoundsWithFontAndFontRenderContext, 
                "Font+FontRenderContext"));
        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont1, 
                TextBoundsTest::computeBoundsWithFontAndFontRenderContext, 
                "Font+FontRenderContext"));

        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont0, 
                TextBoundsTest::computeBoundsWithGlyphVectorLogicalBounds, 
                "GlyphVectorLogicalBounds"));
        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont1, 
                TextBoundsTest::computeBoundsWithGlyphVectorLogicalBounds, 
                "GlyphVectorLogicalBounds"));

        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont0, 
                TextBoundsTest::computeBoundsWithGlyphVectorVisualBounds, 
                "GlyphVectorVisualBounds"));
        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont1, 
                TextBoundsTest::computeBoundsWithGlyphVectorVisualBounds, 
                "GlyphVectorVisualBounds"));

        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont0, 
                TextBoundsTest::computeBoundsWithTextLayout, 
                "TextLayout"));
        f.getContentPane().add(
            new TextBoundsTestPanel(smallFont1, 
                TextBoundsTest::computeBoundsWithTextLayout, 
                "TextLayout"));


        f.setSize(600,800);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static Rectangle2D computeBoundsWithFontMetrics(
        String string, Graphics2D g)
    {
        FontMetrics fontMetrics = g.getFontMetrics();
        Rectangle2D bounds = fontMetrics.getStringBounds(string, g);
        return bounds;
    }

    private static Rectangle2D computeBoundsWithFontAndFontRenderContext(
        String string, Graphics2D g)
    {
        FontRenderContext fontRenderContext =
            new FontRenderContext(g.getTransform(),true, true);
        Font font = g.getFont();
        Rectangle2D bounds = font.getStringBounds(string, fontRenderContext);
        return bounds;
    }

    private static Rectangle2D computeBoundsWithGlyphVectorLogicalBounds(
        String string, Graphics2D g)
    {
        FontRenderContext fontRenderContext = g.getFontRenderContext();
        Font font = g.getFont();
        GlyphVector glyphVector = font.createGlyphVector(
            fontRenderContext, string);
        return glyphVector.getLogicalBounds();
    }

    private static Rectangle2D computeBoundsWithGlyphVectorVisualBounds(
        String string, Graphics2D g)
    {
        FontRenderContext fontRenderContext = g.getFontRenderContext();
        Font font = g.getFont();
        GlyphVector glyphVector = font.createGlyphVector(
            fontRenderContext, string);
        return glyphVector.getVisualBounds();
    }

    private static Rectangle2D computeBoundsWithTextLayout(
        String string, Graphics2D g)
    {
        FontRenderContext fontRenderContext = g.getFontRenderContext();
        Font font = g.getFont();
        TextLayout textLayout = new TextLayout(string, font, fontRenderContext);
        return textLayout.getBounds();        
    }


}


class TextBoundsTestPanel extends JPanel
{
    private final Font textFont;
    private final BiFunction<String, Graphics2D, Rectangle2D> boundsComputer;
    private final String boundsComputerName;

    TextBoundsTestPanel(Font textFont, 
        BiFunction<String, Graphics2D, Rectangle2D> boundsComputer,
        String boundsComputerName)
    {
        this.textFont = textFont;
        this.boundsComputer = boundsComputer;
        this.boundsComputerName = boundsComputerName;
    }

    @Override
    protected void paintComponent(Graphics gr) 
    {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D)gr;
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.BLACK);

        g.drawString("Font size: "+textFont.getSize2D(), 10, 20);
        g.drawString("Bounds   : "+boundsComputerName, 10, 40);

        AffineTransform oldAt = g.getTransform();
        AffineTransform at = AffineTransform.getScaleInstance(50, 50);
        g.transform(at);
        g.translate(1, 2);

        g.setFont(textFont);

        String string = "Test";
        g.drawString(string, 0, 0);

        Rectangle2D bounds = boundsComputer.apply(string, g);
        Shape boundsShape = at.createTransformedShape(bounds);

        g.setTransform(oldAt);

        g.setColor(Color.RED);
        g.translate(50, 100);
        g.draw(boundsShape);
    }
}

这个程序的结果显示在这个截图中:

TextBounds

正如您所看到的,简单的方法对于大小为 0.5 的字体效果很好,但是对于大小为 0.4 的字体突然退出并返回高度为 0.0 的边界。

(旁注:我想知道这是否只是一个错误 - 尽管它可能是由一些内部舍入错误引起的,因为它恰好发生在 0.5 和 0.49 之间的字体大小之间......)

唯一适用于这些较小字体的解决方案是使用 GlyphVector 或 TextLayout 进行计算。但这两种方法都非常昂贵,因为它们需要创建字符串的形状和许多辅助对象。此外,它们只返回视觉边界(即实际形状的边界),而不返回文本的逻辑边界。

是否有任何有效的解决方案来计算小字体字符串的逻辑边界?

最佳答案

您可以先规范化字体。测量然后按字体的真实 size2D 缩放矩形的尺寸。

private static Rectangle2D computeBoundsUsingNormalizedFont(
        String string, Graphics2D g) {
    Font normalizedFont = g.getFont().deriveFont(1f);
    Rectangle2D bounds = normalizedFont.getStringBounds(string, g.getFontRenderContext());

    float scale = g.getFont().getSize2D();
    return new Rectangle2D.Double(bounds.getX() * scale,
            bounds.getY() * scale,
            bounds.getWidth() * scale,
            bounds.getHeight() * scale);
}

Proof

显然你可以缓存规范化的字体并将这个工作隐藏在计算器类中,就像这样:

TextBoundsCalculator textBoundsCalculator = TextBoundsCalculator.forFont(smallFontX);

Rectangle2D bounds = textBoundsCalculator.boundsFor(string, g);

哪里 TextBoundsCalculator:

import java.awt.*;
import java.awt.geom.Rectangle2D;

public final class TextBoundsCalculator {
    private interface MeasureStrategy {
        Rectangle2D boundsFor(String string, Graphics2D g);
    }

    private MeasureStrategy measureStrategy;

    private TextBoundsCalculator(MeasureStrategy measureStrategy) {
        this.measureStrategy = measureStrategy;
    }

    public static TextBoundsCalculator forFont(Font font) {
        if (font.getSize() == 0)
            return new TextBoundsCalculator(new ScaleMeasureStrategy(font));

        // The bug appears to be only when font.getSize()==0.
        // So there's no need to normalize, measure and scale with fonts
        // where this is not the case
        return new TextBoundsCalculator(new NormalMeasureStrategy(font));
    }

    public Rectangle2D boundsFor(String string, Graphics2D g) {
        return measureStrategy.boundsFor(string, g);
    }

    private static class ScaleMeasureStrategy implements MeasureStrategy {
        private final float scale;
        private final Font normalizedFont;

        public ScaleMeasureStrategy(Font font) {
            scale = font.getSize2D();
            normalizedFont = font.deriveFont(1f);
        }

        public Rectangle2D boundsFor(String string, Graphics2D g) {
            Rectangle2D bounds = NormalMeasureStrategy.boundsForFont(normalizedFont, string, g);
            return scaleRectangle2D(bounds, scale);
        }
    }

    private static class NormalMeasureStrategy implements MeasureStrategy {
        private final Font font;

        public NormalMeasureStrategy(Font font) {
            this.font = font;
        }

        public Rectangle2D boundsFor(String string, Graphics2D g) {
            return boundsForFont(font, string, g);
        }

        private static Rectangle2D boundsForFont(Font font, String string, Graphics2D g) {
            return font.getStringBounds(string, g.getFontRenderContext());
        }
    }

    private static Rectangle2D scaleRectangle2D(Rectangle2D rectangle2D, float scale) {
        return new Rectangle2D.Double(
                rectangle2D.getX() * scale,
                rectangle2D.getY() * scale,
                rectangle2D.getWidth() * scale,
                rectangle2D.getHeight() * scale);
    }
}

关于java - Swing 中带有小字体的字符串的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495795/

相关文章:

html - Ubuntu 上的 Helvetica Neue

java - 增加 Firebase Firestore 中的现有值(value)

java - 在 java 中具有子类化的单例

java - 通过服务器调用 Web 服务会导致 java.net.MalformedURLException : no protocol

java - 面板未添加到 GUI

java - 无法在 Jtable 中调用 JTable Cellrenderer

java - 如何获取其他类的值?

java - 一种以恒定速度沿直线移动鸵鸟的有效算法

ios - BoundingRectWithSize - 选择使用的字体和字体大小

java - JDialog标题的字体大小