Scala - 最简单的二维图形,只需将二维数组写入屏幕? [英] Scala - Easiest 2D graphics for simply writing a 2D array to the screen?

查看:30
本文介绍了Scala - 最简单的二维图形,只需将二维数组写入屏幕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于将二维像素阵列写入屏幕,您有什么建议?

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

我首先想到的是一些 SWT 绑定,但还有其他的吗?可能正在处理?

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

推荐答案

Swing 并不太难 - 您可以剪切和粘贴以下内容.如果您不想要颜色或无法绘制到任何大小的窗口,或者它总是相同的大小,您可以稍微简化一下.

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.

定义一个面板类:

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)
    }
  }
}

然后制作一个 Swing 应用程序:

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)
    }
  }
}

您的数据可能类似于

  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
  }

哪个会给你:

您可以轻松地在现有数组上使用 map 函数将其映射到颜色.

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

这篇关于Scala - 最简单的二维图形,只需将二维数组写入屏幕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆