为什么三角形渲染背景颜色超过图像?

时间:2014-02-09 15:24:20

标签: c# .net opengl opentk

我正在显示位图
enter image description here 来自png 800x600但渲染时: image with unwanted triangle

我有一个继承GameWindow的Window类,这里是(我相信)相关的重写方法:

protected override void OnLoad(EventArgs e) {
    base.OnLoad(e);

    GrafxUtils.InitTexturing();
    textureId = GrafxUtils.CreateTextureFromBitmap((Bitmap)currentImage);

    OnResize(null);
    GL.ClearColor(Color.Gray);

}

protected override void OnRenderFrame(FrameEventArgs e) {
    base.OnRenderFrame(e);

    GL.Clear(ClearBufferMask.ColorBufferBit);
    GL.MatrixMode(MatrixMode.Texture);
    GL.LoadIdentity();
    GL.BindTexture(TextureTarget.Texture2D, textureId);
    GL.Begin(PrimitiveType.Quads);

    //  top-left
    GL.TexCoord2(0, 0);
    GL.Vertex2(0, 0);

    //  top-right
    GL.TexCoord2(1, 0);
    GL.Vertex2(currentImage.Width, 0);

    //  bottom-left
    GL.TexCoord2(0, 1);
    GL.Vertex2(0, currentImage.Height);

    //  bottom-right
    GL.TexCoord2(1, 1);
    GL.Vertex2(currentImage.Width, currentImage.Height);

    GL.End();

    SwapBuffers();
}

...和CreateTextureFromBitmap方法:

// utility method from GrafxUtils
public static int CreateTextureFromBitmap(Bitmap bitmap) {
    BitmapData data = bitmap.LockBits(
      new Rectangle(0, 0, bitmap.Width, bitmap.Height),
      ImageLockMode.ReadOnly,
      System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    var tex = GetBoundTexture();
    GL.BindTexture(TextureTarget.Texture2D, tex);
    GL.TexImage2D(
      TextureTarget.Texture2D,
      0,
      PixelInternalFormat.Rgba,
      data.Width, data.Height,
      0,
      OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
      PixelType.UnsignedByte,
      data.Scan0);
    bitmap.UnlockBits(data);
    SetParameters();
    return tex;
}

导致三角形出现的原因是什么?

1 个答案:

答案 0 :(得分:2)

顶点坐标的currentImage.Width / currentImage.Height的使用不正确。它的范围应该是-1到1.在你的情况下,因为你似乎是从0到1(即屏幕的四分之一),左上角应该是(0,0)右上角应该有( 1,0)和bottomleft应该有(0,-1),bottomright应该有(1,-1)。如果你想要全屏四边形,它的范围应该是-1,-1到1,1。

至于您正在观察的奇怪形状,您正在绘制2个三角形,但是缠绕顺序没有处理。即,一个三角形的斜边是从左上到右下,另一个三角形的斜边是从左下到右上。因此形状。你可以看到,例如,

http://msdn.microsoft.com/en-us/library/bb464051.aspx

而且,

Index Buffer Object and UV Coordinates don't play nice