我想用 Java 进行高效的 2D 绘图。我想要某种可以自由绘制的表面,而不必让视图层次结构遍历和更新,这可能会导致卡顿。
我一开始使用了 JPanel 并调用了 repaint() 但我发现它不是最佳的(这就是我问的原因)。我用过的最接近的东西是 Android 的SurfaceView,它给了我一个专用的绘图表面。
为了实现这个专用的绘图表面,我需要使用 OpenGL 还是有任何等效的SurfaceView?
我想用 Java 进行高效的 2D 绘图。我想要某种可以自由绘制的表面,而不必让视图层次结构遍历和更新,这可能会导致卡顿。
我一开始使用了 JPanel 并调用了 repaint() 但我发现它不是最佳的(这就是我问的原因)。我用过的最接近的东西是 Android 的SurfaceView,它给了我一个专用的绘图表面。
为了实现这个专用的绘图表面,我需要使用 OpenGL 还是有任何等效的SurfaceView?
如果您不需要 Accelerated Graphics,则可以在BufferedImagewith上绘制Graphics2D。将数据放入 中后BufferedImage,您可以简单地将 绘制BufferedImage到组件上。这将避免您正在谈论的任何类型的闪烁。
创建 BufferedImage 很简单:
int w = 800;
int h = 600;
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
然后您可以使用图形上下文在其上绘制对象(可能在您自己的渲染函数中):
Graphics2D g = bi.createGraphics();
g.drawImage(img, 0, 0, null);
//img could be your sprites, or whatever you'd like
g.dipose();//Courtesy of MadProgrammer
//You own this graphics context, therefore you should dispose of it.
然后,当您重新绘制组件时,将 BufferedImage 作为一个整体绘制到它上面:
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
它有点像使用 BufferedImage 作为后台缓冲区,然后在完成绘制后,将其重新绘制到组件上。