Ok, this is an old post, but I would like to share my conclusions about direct drawing using Swing / AWT without BufferedImage.
Some kind of drawing, like 3D, is best done when you draw directly in the int [] buffer. After creating the images, you can use an instance of ImageProducer , such as MemoryImageSource , to create the images. I assume that you know how to execute your drawings directly, without using Graphics / Graphics2.
public class MyCanvas extends JPanel implements Runnable { public int pixel[]; public int width; public int height; private Image imageBuffer; private MemoryImageSource mImageProducer; private ColorModel cm; private Thread thread; public MyCanvas() { super(true); thread = new Thread(this, "MyCanvas Thread"); } public void init(){ cm = getCompatibleColorModel(); width = getWidth(); height = getHeight(); int screenSize = width * height; if(pixel == null || pixel.length < screenSize){ pixel = new int[screenSize]; } mImageProducer = new MemoryImageSource(width, height, cm, pixel,0, width); mImageProducer.setAnimated(true); mImageProducer.setFullBufferUpdates(true); imageBuffer = Toolkit.getDefaultToolkit().createImage(mImageProducer); if(thread.isInterrupted() || !thread.isAlive()){ thread.start(); } } public void render(){
Please note that we need a unique instance of MemoryImageSource and Image . Do not create a new image or a new ImageProducer for each frame unless you have resized your JPanel. See the init () method above.
In the rendering stream, set repaint () . In Swing, repaint () will call an overridden paintComponent () , where it will call the render () method, and then ask to update the imageProducer image. Using Image done, draw it using Graphics.drawImage () .
To create a compatible image, use ColorModel when creating the image . I am using GraphicsConfiguration.getColorModel () :
protected static ColorModel getCompatibleColorModel(){ GraphicsConfiguration gfx_config = GraphicsEnvironment. getLocalGraphicsEnvironment().getDefaultScreenDevice(). getDefaultConfiguration(); return gfx_config.getColorModel(); }
Alex Byrth Feb 10 '16 at 4:17 2016-02-10 04:17
source share