RingJavafor Ring

Drawing and images

Java2D on a BufferedImage: shapes, text, a gradient, pixels, a PNG file and a window that shows the picture.

What you will learn#

The program#

samples/UsingJava/tutorials/ch20_painting.ring
# Tutorial 20: drawing and images - Java2D on a BufferedImage, shown in a window and saved as a PNG file
load "java.ring"

using {
	"javax.swing"
	"java.awt"
	"java.awt.image"
	"javax.imageio"
	"java.io"
}

ImageIO = new ImageIO

nW = 400
nH = 260
oImage = (new BufferedImage).@New([nW,nH,1])        # 1 = TYPE_INT_RGB
g = oImage.createGraphics()
g.setRenderingHint(jGetStatic("java.awt.RenderingHints","KEY_ANTIALIASING"),jGetStatic("java.awt.RenderingHints","VALUE_ANTIALIAS_ON"))

# the background: a gradient
g.setPaint((new GradientPaint).@New([0,0,jColor(20,40,90),0,nH,jColor(110,160,230)]))
g.fillRect(0,0,nW,nH)

# shapes: the origin (0,0) is the top left corner
g.setColor(jColor(255,200,40))
g.fillOval(300,20,70,70)                            # the sun
g.setColor(jColor(30,110,50))
g.fillRect(0,200,nW,60)                             # the ground
g.setColor(jColor(150,60,40))
g.fillRect(80,130,110,80)                           # a house
g.setColor(jColor(90,30,20))
g.fillPolygon([jArray("int",[70,135,200]),jArray("int",[135,80,135]),3])
g.setColor(jColor(240,240,240))
g.fillRect(120,160,30,50)

# lines and text
g.setStroke((new BasicStroke).@New([3]))
g.setColor(jColor(255,255,255))
g.drawLine(220,215,380,185)
g.setFont((new Font).@New(["SansSerif",1,22]))
g.drawString("Java2D from Ring",20,35)
g.dispose()

# pixels can be read back
? "pixel at 5,5 has a color: " + (oImage.getRGB([5,5]) != 0)

# save the image as a PNG file and read it again
oFile = (new File).@New([ "painting.png" ])
ImageIO.write(oImage,"png",oFile)
? "file written: " + oFile.exists() + ", " + (oFile.length() > 1000)
oBack = ImageIO.read(oFile)
? "size: " + oBack.getWidth() + " x " + oBack.getHeight()
oFile.delete()

# the window shows the image in a label
oFrame = new JFrame("Painting")
oFrame.setDefaultCloseOperation(2)
oFrame.add(new JLabel(new ImageIcon(oImage)))
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
The picture
ch20_painting.ring

How it works#

The origin (0,0) is the top left corner. jColor(r,g,b) makes a colour. A Polygon takes two Java arrays (jArray("int", ...)). The picture is first drawn on an image in memory, so it can be saved, read back and shown in a window in the same program.

Exercises#

  1. Draw a face.
  2. Save the picture as a JPEG.
  3. Read a file and draw a frame around it.

Next#

Animation

RingJava - use Java classes and methods from Ring programs.