前言

SDL2 说你有时候只想渲染窗口的一部分, 那么你可以使用 viewport 好了, 没啥好说的上代码

代码

package main

import (
    "github.com/veandco/go-sdl2/img"
    "github.com/veandco/go-sdl2/sdl"
)

const (
    W = 670
    H = 620
)

func main() {
    sdl.Init(sdl.INIT_EVERYTHING)
    defer sdl.Quit()

    window, _ := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
        W, H, sdl.WINDOW_SHOWN)
    defer window.Destroy()

    renderer, _ := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
    defer renderer.Destroy()
    renderer.SetDrawColor(128, 128, 128, 255)

    pngImage, _ := img.Load("../asserts/image/texture.png")
    texture, _ := renderer.CreateTextureFromSurface(pngImage)
    pngImage.Free()
    defer texture.Destroy()

    var topLeftViewPort sdl.Rect
    topLeftViewPort.X = 0
    topLeftViewPort.Y = 0
    topLeftViewPort.W = W / 2
    topLeftViewPort.H = H / 2

    var topRightViewPort sdl.Rect
    topRightViewPort.X = W / 2
    topRightViewPort.Y = 0
    topRightViewPort.W = W / 2
    topRightViewPort.H = H / 2

    var bottomViewPort sdl.Rect
    bottomViewPort.X = 0
    bottomViewPort.Y = H / 2
    bottomViewPort.W = W
    bottomViewPort.H = H / 2

    running := true
    for running {
        for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
            switch event.(type) {
            case *sdl.QuitEvent:
                println("Quit")
                running = false
                break
            }
        }
        renderer.Clear()

        renderer.SetViewport(&topLeftViewPort)
        renderer.Copy(texture, nil, nil)

        renderer.SetViewport(&topRightViewPort)
        renderer.Copy(texture, nil, nil)

        renderer.SetViewport(&bottomViewPort)
        renderer.Copy(texture, nil, nil)

        renderer.Present()
        sdl.Delay(16)
    }
}
  1. 这段代码的作用是把窗口分成三部分, 每部分都渲染一张图片
  2. 前面还是一样, 创建一个窗口, 从窗口上创建一个渲染器, 再创建一个 texture
  3. 然后, 创建了 3 个 Rect 类型的 viewport, 分别指向窗口的左上区域, 右上区域和底部区域
  4. 主循环中, 首先 renderer.Clear 设置一下默认颜色
  5. 然后 renderer.SetViewport 设置 viewport 区域, renderer.Copy 把 texture 渲染到该 viewport 区域上
  6. 后面两个同样的方法
  7. 这样你就能在一个窗口上控制不同的三个区域了

源码 https://gitee.com/fcsvr/tank.git