Java AffineTransform使drawString消失

时间:2015-12-13 18:55:19

标签: java graphics2d affinetransform

这太奇怪了。当我创建一个BufferedImage,并且不更改Graphics2D.transform()时,我可以毫无问题地绘制一条线和文本。

当我设置变换时(我将用户空间设置为使用EMU而不是像素),然后我可以使用EMU坐标绘制线条,但我无法绘制文本。

代码在这里:

public void testBitmaps2() throws Exception {

        // no scaling
        BufferedImage image = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = image.createGraphics();
        graphics.setBackground(new Color(0x00FFFFFF, true));
        graphics.clearRect(0, 0, 300, 300);
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        java.awt.Font javaFont = new java.awt.Font("Arial", java.awt.Font.PLAIN, 24);
        graphics.setFont(javaFont);
        graphics.setColor(Color.BLACK);

        graphics.setStroke(new BasicStroke(1));
        graphics.draw(new Line2D.Float(100, 150, 200, 150));
        graphics.drawString("hi there", 100, 150);
        ImageIO.write(image, "png", new File("c:/temp/", "no_scaling.png"));


        // scaling
        image = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB);
        graphics = image.createGraphics();

        // scale to use EMUs, assuming 300DPI image
        AffineTransform scaleToEmus = AffineTransform.getScaleInstance(300f / 914400f, 300f / 914400f);
        graphics.transform(scaleToEmus);

        graphics.setBackground(new Color(0x00FFFFFF, true));
        graphics.clearRect(0, 0, 914400, 914400);
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        javaFont = new java.awt.Font("Arial", java.awt.Font.PLAIN, 24);
        graphics.setFont(javaFont);
        graphics.setColor(Color.BLACK);

        graphics.setStroke(new BasicStroke(914400 / 300));
        graphics.draw(new Line2D.Float(914400 / 3, 914400 / 2, 914400 * 0.666f, 914400 / 2));
        graphics.drawString("hi there", 914400 / 3, 914400 / 2);
        ImageIO.write(image, "png", new File("c:/temp/", "scaling.png"));
    }

1 个答案:

答案 0 :(得分:0)

好的,javadocs错了! The docs say

  

size - Font

的磅值

但是,您需要将其缩放以匹配变换缩放。