斯卡拉 - 最简单的2D图形,写一个二维数组到屏幕? [英] Scala - Easiest 2D graphics for simply writing a 2D array to the screen?

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

问题描述

你有什么建议写像素的二维数组到屏幕?

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?

推荐答案

这不是太硬的秋千 - 你可以剪切和粘贴如下。你可以把它简化一点,如果你不想要的颜色或提请任何大小的窗口的能力,或者如果它总是相同的大小。

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
  }

这将使您:

您可以轻松地使用现有的阵列上的地图函数将其映射到颜色。

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

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

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