Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Easiest 2D graphics for simply writing a 2D array to the screen? [closed]

Tags:

scala

graphics

2d

What do you recommend for writing a 2D array of pixels to the screen?

My first thought is some SWT binding, but are there any others? Processing perhaps?

like image 723
Dominic Bou-Samra Avatar asked Aug 08 '11 00:08

Dominic Bou-Samra


2 Answers

It's not too hard in Swing - you can cut and paste the below. You could simplify it a bit if you don't want colours or the ability to draw to any size window, or if it's always the same size.

Define a Panel class:

class DataPanel(data: Array[Array[Color]]) extends Panel {

  override def paintComponent(g: Graphics2D) {
    val dx = g.getClipBounds.width.toFloat  / data.length
    val dy = g.getClipBounds.height.toFloat / data.map(_.length).max
    for {
      x <- 0 until data.length
      y <- 0 until data(x).length
      x1 = (x * dx).toInt
      y1 = (y * dy).toInt
      x2 = ((x + 1) * dx).toInt
      y2 = ((y + 1) * dy).toInt
    } {
      data(x)(y) match {
        case c: Color => g.setColor(c)
        case _ => g.setColor(Color.WHITE)
      }
      g.fillRect(x1, y1, x2 - x1, y2 - y1)
    }
  }
}

Then make a Swing app:

import swing.{Panel, MainFrame, SimpleSwingApplication}
import java.awt.{Color, Graphics2D, Dimension}

object Draw extends SimpleSwingApplication {

  val data = // put data here

  def top = new MainFrame {
    contents = new DataPanel(data) {
      preferredSize = new Dimension(300, 300)
    }
  }
}

Your data could be something like

  val data = Array.ofDim[Color](25, 25)

  // plot some points
  data(0)(0) = Color.BLACK
  data(4)(4) = Color.RED
  data(0)(4) = Color.GREEN
  data(4)(0) = Color.BLUE

  // draw a circle 
  import math._
  {
    for {
      t <- Range.Double(0, 2 * Pi, Pi / 60)
      x = 12.5 + 10 * cos(t)
      y = 12.5 + 10 * sin(t)
      c = new Color(0.5f, 0f, (t / 2 / Pi).toFloat)
    } data(x.toInt)(y.toInt) = c
  }

Which would give you:

enter image description here

You can easily use a map function on your existing array to map it to colours.

like image 127
Luigi Plinge Avatar answered Nov 06 '22 20:11

Luigi Plinge


I'm going to suggest @n8han's SPDE, which is a Scala "port" of Processing.

http://technically.us/spde/About

There are a ton of examples here:

https://github.com/n8han/spde-examples

like image 3
tylerweir Avatar answered Nov 06 '22 20:11

tylerweir