使用 F# 绘制简单图形的最简单方法是什么?
我想可视化一个动态系统(我的用例的一个简化示例是以每帧一个像素的速度从屏幕一侧到另一侧的红色方块),所以我需要一种方法来绘制简单的几何形状。
由于我会定期更新图片,因此可能需要一种避免闪烁的机制。
标准解决方案似乎是System.Drawing。我整理了一个可行的解决方案,但代码过于复杂(似乎需要System.Windows.Forms,没有直接的方法可以将图形放入 Windows 中吗?),对于简单的任务来说不是很好,这让我认为可能存在更好的工具.
我做错了什么,有没有一种简单的方法来绘制和更新图片System.Drawing?或者有没有更适合我需求的图书馆?
一种解决方案是使用MonoGame。这是一个成熟的游戏开发框架,但它可以用作.NET中的通用渲染器。许多其他解决方案要么不是跨平台的,要么是低级的(想想 OpenGL)。
这是一个 F# 脚本,用于创建一个包含移动红色框的窗口:
#r "nuget: MonoGame.Framework.DesktopGL, 3.8.1.303"
open Microsoft.Xna.Framework
open Microsoft.Xna.Framework.Graphics
type RedBoxApp() as this =
inherit Game()
let graphicsManager = new GraphicsDeviceManager(this)
let mutable spriteBatch = Unchecked.defaultof<SpriteBatch>
let mutable pixel = Unchecked.defaultof<Texture2D>
with
override this.Initialize() =
this.IsMouseVisible <- true
this.IsFixedTimeStep <- true
this.Window.Title <- "Red Box"
base.Initialize()
override this.LoadContent() =
graphicsManager.PreferredBackBufferWidth <- 640
graphicsManager.PreferredBackBufferHeight <- 480
graphicsManager.ApplyChanges()
spriteBatch <- new SpriteBatch(this.GraphicsDevice)
pixel <- new Texture2D(this.GraphicsDevice, 1, 1)
pixel.SetData([| Color.White |])
override this.Draw(gameTime : GameTime) =
this.GraphicsDevice.Clear(Color.CornflowerBlue)
let squareLeft = 64.0 + gameTime.TotalGameTime.TotalSeconds * 60.0
spriteBatch.Begin()
spriteBatch.Draw(pixel, Rectangle(int squareLeft, 64, 64, 64), Color.Red)
spriteBatch.End()
let app = new RedBoxApp()
app.Run()
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,API 非常命令式且面向对象。然而,可以在此基础上构建更具声明性的层。