Skip to content

Instantly share code, notes, and snippets.

@Maksim-Zhuravlev Maksim-Zhuravlev/render.scala Secret
Created Apr 17, 2016

Embed
What would you like to do?
Example of rendering 2D graphics in Scala
import swing.{Panel, MainFrame, SimpleSwingApplication}
import java.awt.{Color, Graphics2D, Dimension}
import java.awt.image.BufferedImage
class DataPanel(data: Array[Array[Color]]) extends Panel {
override def paintComponent(g: Graphics2D) {
val width = data.length
val height = data.map(_.length).max
val dx = g.getClipBounds.width.toFloat / width
val dy = g.getClipBounds.height.toFloat / height
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)
}
/* Alternative
val i = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
for {
x <- 0 until data.length
y <- 0 until data(x).length
} {
data(x)(y) match {
case c: Color => i.setRGB(x, y, data(x)(y).getRGB)
case _ => i.setRGB(x, y, Color.WHITE.getRGB)
}
}
g.drawRenderedImage(i, java.awt.geom.AffineTransform.getScaleInstance(dx, dy))
*/
}
}
object render extends SimpleSwingApplication {
val width = 25;
val height = 25;
val scale = 8;
val data = Array.ofDim[Color](width, height)
// plot some points
data(0)(0) = Color.BLACK
data(4)(4) = Color.RED
data(0)(4) = Color.GREEN
data(4)(0) = Color.BLUE
def top = new MainFrame {
contents = new DataPanel(data) {
preferredSize = new Dimension(width * scale, height * scale)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.