Java - Creating an image

Timr picture Timr · Apr 5, 2013 · Viewed 10.4k times · Source

I'm currently working on a game in Java and am trying to create a background without using any image files. The image consists of a square split into 4 triangles, each of which is a different color.

If anyone could point me towards some was of using Graphics2D and then saving it to a BufferedImage, that would be great.

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Apr 5, 2013

I recommend:

  • First create a BufferedImage using the constructor that takes three ints: a width, height, and a BufferedImage type, BufferedImage.TYPE_INT_ARGB would probably work well, and the width and height will likely be constants in your program.
  • You would extract a Graphics2D object out of the BufferedImage by calling its createGraphics() method.
  • Then draw with the Graphics object using its drawXXX(...) methods of which you have many to select from.
  • To change color, simply call setColor(Color c) on your Graphics/Graphics2D object.
  • When done drawing, be sure to dispose of your Graphics object via its dispose() method.
  • Edit as per Adrian Blackburn, check out the BufferedImage Tutorial as part of the standard Oracle Java tutorials.