golang-ui / nuklear

This project provides Go bindings for nuklear.h — a small ANSI C GUI library.
https://github.com/vurtun/nuklear
MIT License
1.57k stars 98 forks source link

Any example on how to display images? #51

Open Chownie opened 6 years ago

Chownie commented 6 years ago

Looking at Nuklear and the godoc for this project I'd thought that perhaps I load images via the standard library's image.Image and then pass an unsafe pointer to the loaded struct but this doesn't seem to be the case.

I can't quite seem to find how it's done, how do you load and use images with these Go bindings?

xlab commented 6 years ago

@Chownie You should bind it to a texture. e.g. https://github.com/xlab/libvpx-go/blob/master/cmd/webm-player/view.go#L255

jkvatne commented 6 years ago

I made a function based on above example. Call it during setup/initialization:

// NkImageFromRgba converts RGBA image to NkImage (texture)
// Call with tex=0 for first time use, then keep tex for later use.
func NkImageFromRgba(tex *uint32, rgba *image.RGBA) nk.Image {
    gl.Enable(gl.TEXTURE_2D)
    if *tex == 0 {
        gl.GenTextures(1, tex)
    }
    gl.ActiveTexture(gl.TEXTURE0)
    gl.BindTexture(gl.TEXTURE_2D, *tex)
    gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST)
    gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR_MIPMAP_NEAREST)
    gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
    gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
    gl.TexImage2D(
        gl.TEXTURE_2D,
        0,                         // Level of detail, 0 is base image level
        gl.RGBA8,                  // Format. COuld ge RGB8 or RGB16UI
        int32(rgba.Bounds().Dx()), // Width
        int32(rgba.Bounds().Dy()), // Height
        0,                // Must be 0
        gl.RGBA,          // Pixel data format of last parameter rgba,Pix, could be RGB
        gl.UNSIGNED_BYTE, // Data type for of last parameter rgba,Pix, could be UNSIGNED_SHORT
        gl.Ptr(rgba.Pix)) // Pixel data
    gl.GenerateMipmap(gl.TEXTURE_2D)
    return nk.NkImageId(int32(*tex))
}

Then, in the drawing loop, call

    nk.NkImage(winInfo.Ctx, nkLogo)

This function should be part of the library, in etc.go.

xlab commented 6 years ago

@jkvatne A small PR is appreciated, let's add it to etc?