Dedicated drawing surface in Java?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 10:19:52

问题


I want to do efficient 2D drawing in Java. I would like to have some kind of surface which I may draw freely without having to let the view hierarchy traverse and update, which may cause stutter.

I have used a JPanel at first and called repaint() but I find it not to be optimal (and it is the reason I ask). The closest thing I have worked with is the Android's SurfaceView and it gives me a dedicated drawing surface.

To achieve this dedicated drawing surface, do I need to use OpenGL or is there any equivalent SurfaceView?


回答1:


If you don't need Accelerated Graphics, you can draw onto a BufferedImage with Graphics2D. Once you have your data in the BufferedImage, you can simply paint the BufferedImage onto the component. This will avoid any sort of flickering you are talking about.

Creating the BufferedImage is easy:

int w = 800;
int h = 600;
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

Then you can draw objects onto it with a graphics context (Possibly in your own render function):

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.

Then when you repaint your component, you draw the BufferedImage onto it as one piece:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(bi, 0, 0, null);
}

Its sort of like using BufferedImage as a back buffer, and then once you are done drawing to it, you repaint it onto the component.



来源:https://stackoverflow.com/questions/18074780/dedicated-drawing-surface-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!