为什么java.awt.Graphics.drawLine特别慢?

时间:2015-06-16 07:21:45

标签: java swing graphics2d

我正在尝试实现以下' grid'布局。

CompleteImage

该类正在扩展 java.awt.Canvas ,并在paint函数中绘制这些形状(或行)。为什么选择帆布?检查here,尝试初始化做类似事情。

更新 MCVE 代码以获取上述'布局':

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

@SuppressWarnings("serial")
public class SO_MCVE extends JPanel {

    private DrawingCanvas _drawingCanvas = null;

    private JButton repaintBtn;

    public SO_MCVE() {
        super(new BorderLayout());

        _drawingCanvas = new DrawingCanvas();
        _drawingCanvas.setSize(new Dimension(600, 600));

        JLabel repaintLabel = new JLabel(
                "<html><div style=\"text-align: center;\">" +
                "REPAINT</html>");
        repaintLabel.setHorizontalAlignment(
                SwingConstants.CENTER);

        repaintBtn = new JButton();
        repaintBtn.add(repaintLabel);
        repaintBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                _drawingCanvas.triggerRepaint();
            }
        });

        add(_drawingCanvas, BorderLayout.CENTER);
        add(repaintBtn, BorderLayout.PAGE_END);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("StackOverflow MCVE for drawLine");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new SO_MCVE());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}

@SuppressWarnings("serial")
class DrawingCanvas extends Canvas {

    public static final Color lightGreen = new Color(0, 255, 0, 180);
    public static final BasicStroke STROKE1PX = new BasicStroke(1.0f);
    public static final BasicStroke STROKE3PX = new BasicStroke(3.0f);

    private static final int LEFT = 50;
    private static final int RIGHT = 550;
    private static final int TOP = 50;
    private static final int BOTTOM = 550;

    private static final double WIDTH = 500.00d;
    private static final double HEIGHT = 500.00d;

    public DrawingCanvas() {

        setBackground(Color.BLACK);
    }

    public void paint(Graphics g) {
        update(g);
    }

    public void triggerRepaint() {
        repaint();
    }

    public void update(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;
        Dimension dim = getSize();
        int w = (int) dim.getWidth();
        int h = (int) dim.getHeight();

        // Clears the rectangle that was previously drawn
        g2.setPaint(Color.BLACK);
        g2.fillRect(0, 0, w, h);

        drawLines(g2, w, h);
    }

    /** Draw the lines marking the x-y limits **/
    private void drawLines(Graphics2D g2, int w, int h) {

        long start = System.nanoTime();
        System.out.println("Start of drawLines(): " + start);

        // Thick lines
        g2.setPaint(Color.GREEN);
        g2.setStroke(STROKE3PX);
        g2.drawLine(LEFT, 0, LEFT, h);
        g2.drawLine(RIGHT, 0, RIGHT, h);
        g2.drawLine(0, TOP, w, TOP);
        g2.drawLine(0, BOTTOM, w, BOTTOM);

        System.out.println("Done drawing thick lines!");
        long end = System.nanoTime();
        System.out.println("Time taken (ns): " +
                (end - start) + ", Time taken(ms): " +
                ((end - start)/1000/1000));
        start = end;

        // Thin vertical lines
        g2.setPaint(lightGreen);
        g2.setStroke(STROKE1PX);
        int wInc = ((int) WIDTH) / 50;
        for(int i = LEFT; i <= RIGHT; i += wInc) {
            g2.drawLine(i, TOP, i, BOTTOM);
        }

        System.out.println("Done drawing vertical lines!");
        end = System.nanoTime();
        System.out.println("Time taken (ns): " +
                (end - start) + ", Time taken(ms): " +
                ((end - start)/1000/1000));
        start = end;

        // Thin horizontal lines
        g2.setPaint(lightGreen);
        g2.setStroke(STROKE1PX);
        int hInc = ((int) HEIGHT) / 50;
        for(int i = TOP; i <= BOTTOM; i += hInc) {
            g2.drawLine(LEFT, i, RIGHT, i);
        }

        System.out.println("Done drawing horizontal lines!");
        end = System.nanoTime();
        System.out.println("Time taken (ns): " +
                (end - start) + ", Time taken(ms): " +
                ((end - start)/1000/1000));

        System.out.println();
    }
}

上面显示的代码存在的问题是,每当我调用repaint()时,渲染这些行需要一段时间(大约3秒钟)。
按&#34;重绘&#34;按钮在MCVE中触发重绘。
这些线将逐一慢慢绘制,如下图所示:

Halfway

所以问题是:
drawLine这么慢的原因吗?我尝试在类似的for循环中使用g2.draw(一些Ellipse2D.Double ..)绘制尽可能多的(如果不是更多)省略号,并且没有问题。

注意:使用jre1.7.0_25,Windows 7,Eclipse
使用System.nanoTime()的简单基准测试:

Done drawing thick lines!
Time taken (ns): 8858966, Time taken(ms): 8
Done drawing vertical lines!
Time taken (ns): 3649188968, Time taken(ms): 3649
Done drawing horizontal lines!
Time taken (ns): 106730282, Time taken(ms): 106

注意:绘制&#39;细垂直线&#39;是永远的!

更新:
注意:使用jre1.8.0_11,Windows 7,Eclipse
使用System.nanoTime()的简单基准测试:

Done drawing thick lines!
Time taken (ns): 110027, Time taken(ms): 0
Done drawing vertical lines!
Time taken (ns): 185567, Time taken(ms): 0
Done drawing horizontal lines!
Time taken (ns): 195419, Time taken(ms): 0

注意:使用jre1.8.0_45,Windows 7,Eclipse
使用System.nanoTime()的简单基准测试:

Done drawing thick lines!
Time taken (ns): 6716121, Time taken(ms): 6
Done drawing vertical lines!
Time taken (ns): 2427676380, Time taken(ms): 2427
Done drawing horizontal lines!
Time taken (ns): 83030042, Time taken(ms): 83
  

显然, jre1.8.0_11 效果很好?

我如何运行不同的jre版本(不确定我是否正确执行!):

VersionSwitch

谢谢! :)

2 个答案:

答案 0 :(得分:4)

像Michael Dibbets建议并使用缓冲一样。

我将the SO_MCVE.update(Graphics g)方法替换为绘制到屏幕外缓冲区然后绘制缓冲区的方法:

public void update(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;
    Dimension dim = getSize();
    int w = (int) dim.getWidth();
    int h = (int) dim.getHeight();

    // Create the buffer
    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D ig2 = image.createGraphics();

    // Paint everythign on the buffer
    // Clears the rectangle that was previously drawn
    ig2.setPaint(Color.BLACK);
    ig2.fillRect(0, 0, w, h);

    drawLines(ig2, w, h);

    // Paint the buffer
    g2.drawImage(image, 0, 0, null);
}
  

drawLines()的开始:1832687816359773
  做了粗线!
  所用时间(ns):2212913,所用时间(ms):2
  完成绘制垂直线!
  所用时间(ns):37676442,所用时间(ms):37
  完成绘制水平线!
  所用时间(ns):6453455,所用时间(ms):6

如果您想提高效率,可以将缓冲的图像存储为属性,并在尺寸发生变化时将其替换。

那就是说,绘制垂直线需要比水平线更长的时间是非常有趣的。在使用调试器和分析器挖掘SunGraphics2D的内部结构后,我仍然无法解释它。

答案 1 :(得分:4)

似乎是Color lightGreen = new Color(0, 255, 0, 180);中导致此行为的 alpha

删除alpha会立即渲染线条。如果你需要alpha,那么一个解决方案是调整渲染提示。

实施例

public void update(Graphics g) {

  Graphics2D g2 = (Graphics2D) g;
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  RenderingHints.VALUE_ANTIALIAS_ON);

// ...