(ns view.core
(:import (java.awt.image BufferedImage)
(java.util Random)
(java.awt Point Color AlphaComposite)
(java.io File)
(javax.imageio ImageIO)))
(defn make-image
[]
(let [width 500
height 500
img (BufferedImage. width height BufferedImage/TYPE_INT_ARGB)
g (.createGraphics img)]
; do the graphics processing here
(.setColor g Color/WHITE)
(.fillRect g 0 0 width height)
(let [rand (Random.)
component-width 25
component-height 25]
(letfn [(fillRandomOval []
(let [point (Point.
(.nextInt rand (- width component-width))
(.nextInt rand (- height component-height)))]
(.fillOval
g
(.-x point)
(.-y point)
component-width
component-height)))]
(.setColor g (new Color 255 0 0 196))
(dotimes [i 100]
(fillRandomOval))
(.setColor g (new Color 0 0 255 64))
(dotimes [i 100]
(fillRandomOval))))
; dispose the graphics
(.dispose g)
; return the image
img))
(defn main
[]
(let [img (make-image)]
(ImageIO/write
img
"png"
(File. (str (System/getProperty "user.home") "/Media/random.png")))))
Of course, for this example we use Image I/O to store the image we produce, because doing so ensures we won't lose any information about the image we are producing.
Unlike in the previous examples, make image here is not a pure function: it produces different results for the same arguments depending upon the time it is called. This is an issue I will have to discuss when I talk about the relationship between functional programming and graphics.
Thursday, June 2, 2022
Explorations in randomness
The next example uses Java 2D to create a random image. This demonstrates the combiantion of 2D graphics and randomness.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment