Windows.Forms和重绘位图

3

我正在实现一个游戏机模拟器,就像之前很多人一样。

我正在尝试实现PPU,并使用代表屏幕的类来完成这个过程。

// needed because VS can't find it as dependency
#r "nuget: System.Windows.Forms"
open System
open System.Windows.Forms
open System.Drawing

type Screen(title, width : int, height : int) as screen =
    inherit Form()
    
    let mutable canvas = new Bitmap(width, height)

    do
        // set some attributes of the screen
        screen.Size <- new Size(width, height)
        screen.Text <- title

    interface IDisposable with
        member S.Dispose() = (canvas :> IDisposable).Dispose()

    override S.OnPaint e =
        e.Graphics.DrawImage(canvas,0,0) // here
        base.OnPaint(e)

    member S.Item
        with get (w, h) = canvas.GetPixel(w,h)
        and set (w,h) pixel = canvas.SetPixel(w,h,pixel)

但是我无法在重新绘制位图后更新屏幕,它不显示重绘的图像。

重新绘制

let main () =
    let screen = new Screen("gameboy",800,600)
    Application.Run(screen)
    // test example
    for i in 0 .. 300 do
        screen.[i,i] <- Drawing.Color.Black
    (screen :> Form).Refresh()

即如何在位图更新后使其重新绘制?
1个回答

4
在调用 Application.Run 之后,您不能进行任何图形操作,因为它直到用户关闭主窗体才会结束。相反,您可以创建一个事件处理程序,在主窗体加载后调用它,像这样:
let main argv =
    let screen = new Screen("gameboy",800,600)
    screen.Load.Add(fun _ ->
        for i in 0 .. 300 do
            screen.[i,i] <- Drawing.Color.Black)
    Application.Run(screen)
    0

谢谢。我应该在哪里放置屏幕刷新/无效调用以使其重新绘制? - kam
如果你想做动画,你可能需要创建一个计时器,然后在计时器的事件处理程序中使其失效。这个Stack Overflow问题有一些有用的细节。 - Brian Berns

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接