Question

I am coloring my 3D control with background color , instead i want to have a Background image. Is it possible? Below is the code used for background color.

GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Disable(EnableCap.DepthTest);
GL.Disable(EnableCap.Lighting);
GL.Begin(BeginMode.Quads);
GL.Color4(convertColor(Color.DimGray));
GL.Vertex2(-1.0, -1.0);
GL.Vertex2(1.0, -1.0);
GL.Color4(convertColor(Color.Violet));
GL.Vertex2(1.0, 1.0);
GL.Vertex2(-1.0, 1.0);
GL.End();
Was it helpful?

Solution

Yes, you can render a background image.

How to load a texture from disk (OpenTK documentation):

using System.Drawing;
using System.Drawing.Imaging;
using OpenTK.Graphics.OpenGL;

static int LoadTexture(string filename)
{
    if (String.IsNullOrEmpty(filename))
        throw new ArgumentException(filename);

    int id = GL.GenTexture();
    GL.BindTexture(TextureTarget.Texture2D, id);

    Bitmap bmp = new Bitmap(filename);
    BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0,
        OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);

    bmp.UnlockBits(bmp_data);

    // We haven't uploaded mipmaps, so disable mipmapping (otherwise the texture will not appear).
    // On newer video cards, we can use GL.GenerateMipmaps() or GL.Ext.GenerateMipmaps() to create
    // mipmaps automatically. In that case, use TextureMinFilter.LinearMipmapLinear to enable them.
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

    return id;
}

How to draw the texture (complete source code):

GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();

GL.Enable(EnableCap.Texture2d);
GL.BindTexture(TextureTarget.Texture2D, texture);

GL.Begin(PrimitiveType.Quads);

GL.TexCoord2(0.0f, 1.0f); GL.Vertex2(-1.0f, -1.0f);
GL.TexCoord2(1.0f, 1.0f); GL.Vertex2(1.0f, -1.0f);
GL.TexCoord2(1.0f, 0.0f); GL.Vertex2(1.0f, 1.0f);
GL.TexCoord2(0.0f, 0.0f); GL.Vertex2(-1.0f, 1.0f);

GL.End();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top