【问题标题】:Draw Graphics2D to another Graphics2D将 Graphics2D 绘制到另一个 Graphics2D
【发布时间】:2013-08-21 08:42:39
【问题描述】:

是否可以从一个Graphics2D 绘制到另一个Graphics2D

让我解释一下。 我有打印问题,当我在屏幕上显示JTextAreaJTextPanel 时,内部使用了sun.java2d.SunGraphics2D,但是当我打印时使用了sun.print.PeekGraphicssun.awt.windows.WPathGraphics。 问题出在某种字体上,比如 Arial。在某些尺寸中,线条被切割。 我尝试了很多方法来在打印中呈现文本,Graphics2D.drawStringSwingUtilities2.drawStringTextLayout.drawString,但在某些情况下,线条仍然被剪切,或者线条没有被剪切,但某种理由会使空白消失。

所以我的想法是尝试使用 sun.java2d.SunGraphics2D 渲染组件并通过sun.print.PeekGraphicssun.awt.windows.WPathGraphics 将表面“复制”到打印机。

提前致谢。

【问题讨论】:

    标签: java swing printing graphics2d text-rendering


    【解决方案1】:

    是的,这是可能的,这就是在许多 Java 游戏中实现双缓冲的方式。您需要的是 Graphics2D 的 drawImage() 方法,该方法接受另一个 Graphics2D 对象进行绘制。例如来自我的一个小游戏:

       private Main(){
            ...
            /* Create the backbuffer as a BufferedImage object */
            this.doubleBuffer = new BufferedImage(this.WIDTH, this.HEIGHT, BufferedImage.TYPE_INT_RGB);
            /* create a Graphics 2D object to draw INTO this backbuffer */
            this.doubleBufferG2D = (Graphics2D) doubleBuffer.createGraphics();
            ...
        }
    

    其他地方:

    /*Now lets draw the backbuffer INTO the screen */
    g2d.drawImage(doubleBuffer, null , 0, 0);
    

    编辑:嘿,我意识到它与上面的不完全一样......让我考虑一下。

    Edit2:好吧,上面仍然可以用作示例,但是从一个 Graphics2D 绘制到另一个的步骤顺序应该是这样的: 1. 使用 drawGraphics() 从 Graphics2D 对象到 Image/BufferedImage 对象。 2. 从上面的 Image/BufferedImage 中,使用 itscreateGraphics() 提取其成员 Graphics2D 对象。

    【讨论】:

    • Graphics2D.drawGraphics() 不存在。
    【解决方案2】:

    看起来你可以做以下两件事之一:

    • 在图像上创建 Graphics2D,进行渲染,然后将图像绘制到另一个 Graphics2D

    • 或使用 Graphics.create() 方法从原始 Graphics2D 创建 Graphics2D,然后进行渲染。

    【讨论】:

    • 我将放弃第一种方法。将矢量(字体)光栅化到图像中会导致精度损失,图像也会消耗更多内存。请您举例说明第二种方法吗?
    • 我没有这样的例子 - 所以,这是我迄今为止找到的最好的答案:stackoverflow.com/questions/14088613/…。特别是,你需要做的事情是困难的。由于不同 DPI 下字体渲染的差异,即使您做对了所有事情,也可能会在打印中截断适合屏幕框的内容,反之亦然。大约 20 年前,我不得不深入了解 Win API - 持久的印象是它非常重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多