开发者

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

开发者 https://www.devze.com 2023-03-26 07:23 出处:网络
Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 7 years ago.

开发者_开发百科 Improve this question

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?


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:

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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消