proofit404
proofit404

Reputation: 386

Rendering png image sequence in Clojure

How I can create window all content of which is an animation produced with png sequence?

I can't find any appropriate articles for this theme. Or if I plan to do little game in Clojure, maybe it wood be better to use any java game engine? What will you use for this aim?

Upvotes: 1

Views: 651

Answers (1)

Jan
Jan

Reputation: 11726

Let's adapt an example from Wikibooks.

(import '(javax.swing JFrame JPanel)
        '(java.awt Dimension Toolkit)
        '(java.net URL))

(def url
  (URL. "http://www.gravatar.com/avatar/70fa7ca20ce9cbf4c97bb9538034cef7?s=200&d=identicon&r=PG"))

(def avatar
  (ref (-> (Toolkit/getDefaultToolkit) (.getImage url))))

(defn image
  []
  @avatar)

(defn make-panel []
  (let [panel (proxy [JPanel] []
                (paintComponent [g]
                  (.drawImage g (image) 0 0 this)))]
    (doto panel
      (.setPreferredSize (Dimension. 200 200)))))

(defn make-frame [panel]
  (doto (new JFrame)
    (.add panel)
    .pack
    .show))

(def frame
  (make-frame (make-panel)))

Now update the avatar ref to a new image using ref-set. Remember to repaint the frame afterwards.

(dosync
  (ref-set avatar (-> (Toolkit/getDefaultToolkit) (.getImage "image.png"))))

(.repaint frame)

Now let's animate it.

(def images
  (cycle (map #(-> (Toolkit/getDefaultToolkit) (.getImage %))
              ["1.png" "2.png" "3.png"])))

(loop [coll images]
  (when (.isVisible frame)
    (dosync (ref-set avatar (first coll)))
    (.repaint frame)
    (Thread/sleep 100)
    (recur (rest coll))))

I hope it's enought to get you started.

Speaking of game engines for the Java ecosystem, you might want to take a look at lwjgl.

Upvotes: 5

Related Questions