Go SDL2 游戏开发入门10-像素融合与透明度
前言
上一节讲了颜色调制, 这一节我们讲透明度的转换 由于透明度的变化会使得两张图片的融合, 我们还需要设置容和标志
代码
package main import ( "github.com/veandco/go-sdl2/img" "github.com/veandco/go-sdl2/sdl" ) type Texture struct { t *sdl.Texture } func (this *Texture) LoadFromFile(path string) bool { img, err := img.Load(path) if err != nil { panic(err) } this.t, err = Grender.CreateTextureFromSurface(img) if err != nil { panic(err) } img.Free() return true } func (this *Texture) Render(x, y int32, src *sdl.Rect) { if src == nil { Grender.Copy(this.t, nil, nil) } else { dst := &sdl.Rect{X: x, Y: y, W: src.W, H: src.H} Grender.Copy(this.t, src, dst) } } func (this *Texture) setColor(r, g, b uint8) { this.t.SetColorMod(r, g, b) } func (this *Texture) SetAlpha(a uint8) { this.t.SetAlphaMod(a) } func (this *Texture) SetBlendMode(blend sdl.BlendMode) { this.t.SetBlendMode(blend) } func (this *Texture) Free() { this.t.Destroy() } const ( W = 670 H = 620 ) var ( Gwindow *sdl.Window Grender *sdl.Renderer backTexture *Texture upTexture *Texture ) func init() { sdl.Init(sdl.INIT_EVERYTHING) Gwindow, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, W, H, sdl.WINDOW_SHOWN) if err != nil { panic(err) } Grender, err = sdl.CreateRenderer(Gwindow, -1, sdl.RENDERER_ACCELERATED) if err != nil { panic(err) } Grender.SetDrawColor(128, 128, 128, 255) backTexture, upTexture = &Texture{}, &Texture{} backTexture.LoadFromFile("../asserts/image/fadein.png") upTexture.LoadFromFile("../asserts/image/fadeout.png") upTexture.SetBlendMode(sdl.BLENDMODE_BLEND) } func main() { a := 255 running := true for running { for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch t := event.(type) { case *sdl.QuitEvent: println("Quit") running = false break //case *sdl.KeyboardEvent: case *sdl.KeyboardEvent: if t.State == sdl.PRESSED { switch t.Keysym.Sym { case sdl.K_q: if a+32 > 255 { a = 255 } else { a += 32 } fmt.Println("alpha = ", a) case sdl.K_w: if a-32 < 0 { a = 0 } else { a -= 32 } } } } } Grender.Clear() backTexture.Render(0, 0, nil) upTexture.SetAlpha(uint8(a)) upTexture.Render(0, 0, nil) Grender.Present() sdl.Delay(16) } free() } func free() { backTexture.Free() upTexture.Free() Grender.Destroy() Gwindow.Destroy() sdl.Quit() }
- 首先在 Texture 结构体中添加两个方法, SetAlpha 和 SetBlendMode, 一个设置 alpha 值, 一个设置 blend 融合标志
- 然后添加两张图片
- 主循环里根据按键不同对 alpha 值进行修改, 最后渲染出来
- 没有很多东西, 很容易理解