UVTC's Blog

2013-03-31

Been using Quil lately for a small fun evening project. It wasn’t obvious to me how to get it to render some text, so here’s an example of what worked for me:

(ns text-example.core
  (require [quil.core :as q])
  (:gen-class))

(def screen-width  640)
(def screen-height 480)

(def blue   [53 108 237])
(def yellow [235 229 20])

(declare exit-on-close)
(declare setup)
(declare draw)

(defn -main
  "Example of rendering text with quil."
  [& args]
  ;; Work around dangerous default behaviour in Clojure.
  (alter-var-root #'*read-eval* (constantly false))
  ;; Make quil exit when we close the app.
  (exit-on-close (q/sketch :title "Text Example"
                           :setup setup
                           :draw  draw
                           :size  [screen-width
                                   screen-height])))

(defn exit-on-close
  [the-sketch]
  (let [the-frame (-> the-sketch
                      .getParent
                      .getParent
                      .getParent
                      .getParent)]
    (.setDefaultCloseOperation the-frame
                               javax.swing.JFrame/EXIT_ON_CLOSE)))

(defn setup
  []
  (q/smooth)
  (q/frame-rate 20)
  (q/text-font (q/create-font "DejaVu Sans" 28 true))
  (q/background 20))  ; dark screen background

(defn draw
  []
  ;; `stroke` sets the stroke color (not the color of the letters).
  (apply q/stroke yellow)

  ;; Note that the border (the stroke) is centered on the point where
  ;; the shape is anchored.
  (q/stroke-weight 20)

  ;; `fill` sets the fill color (text color, and color inside shapes).
  (apply q/fill blue)

  ;; xy coords specify the top left of the rectangle.
  (q/rect 300  ; x
          100  ; y
          150  ; width
          200) ; height

  ;; xy coords specify the *bottom* left of where the text begins.
  (q/text "Hi there"
          300   ; x
          100)  ; y

  ;; One last dark dot to show exactly where that (300, 100)
  ;; point is.
  (q/stroke 20)        ; Use `stroke` to set color of a point.
  (q/stroke-weight 3)  ; Yes, stroke-weight determines point size.
  (q/point 300 100))