<p>I'm very new to SDL and I'm trying to write a function that allows me to do pixel art game or pure pixel drawing in SDL. I tried piecing together a working program that would atleast allow me to draw pixel at every iteration and make a simple animation.</p>
<p><a href="https://gist.github.com/boarpig/d09e419b427c8c2da440">Here's what I did so far</a> </p>
<p>But I ran into trouble because I couldn't make heads or tail from go's pointer and int conversions. What I understand is that texture.Lock() is supposed to give me a pointer to pixel data that I can draw into and then save it with texture.Update and then Unlock it.</p>
<p>Thank you very much!</p>
<hr/>**评论:**<br/><br/>calebdoxsey: <pre><p>I don't think you're far off:</p>
<pre><code>var pixels unsafe.Pointer
var pitch int
err = texture.Lock(nil, &pixels, &pitch)
if err != nil {
panic(err)
}
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
(*[w * h]uint32)(pixels)[y*(pitch/4)+x] = 100 // whatever color you want
}
}
texture.Update(nil, pixels, pitch)
texture.Unlock()
</code></pre>
<p>The main differences:</p>
<ol>
<li>divide the pitch by 4 since its in bytes but you are using uint32s</li>
<li>lock / unlock outside of the loop</li>
<li>use two loops for x & y so the break condition is obvious</li>
</ol>
<p><code>w</code> and <code>h</code> have to be constant in this example, but it really just needs to be a large number. This is a general trick when using unsafe pointers which you can also use to do zero-cost conversions: <a href="https://github.com/calebdoxsey/tutorials/blob/master/integration/shm/main.go#L86" rel="nofollow">https://github.com/calebdoxsey/tutorials/blob/master/integration/shm/main.go#L86</a>.</p>
<p>I'd recommend making something like a Pixels or Bitmap struct which you can use for your drawing code, then passing that into the SDL methods. It could be as simple as:</p>
<pre><code>type Pixels struct { unsafe.Pointer }
</code></pre>
<p>And just add methods like:</p>
<pre><code>func (px Pixels) Get(x, y int) uint32
func (px Pixels) Set(x, y int, color uint32)
</code></pre>
<p>So you can hide the type conversions.</p></pre>boarhog: <pre><p>Thanks, it seems to work now. Thanks a lot for you help!</p>
<p>Here's a updated copy</p>
<p><a href="https://gist.github.com/boarpig/d09e419b427c8c2da440" rel="nofollow">https://gist.github.com/boarpig/d09e419b427c8c2da440</a></p>
<p>I'll look into abstracting those pixels later :)</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传