我的目标是在GL_Control(一个GUI控件)上使用C#中的OpenTK绘制东西,并且每次调用paint事件时也将其保存到Bitmap对象中。我有以下代码:
private void glControl1_Paint(object sender, PaintEventArgs e)
{
// do lots of drawing here
GL.Finish();
GL.Flush();
glControl1.SwapBuffers();
gl_image = TakeScreenshot();
}
public Bitmap TakeScreenshot()
{
if (GraphicsContext.CurrentContext == null)
throw new GraphicsContextMissingException();
int w = glControl1.ClientSize.Width;
int h = glControl1.ClientSize.Height;
Bitmap bmp = new Bitmap(w, h);
System.Drawing.Imaging.BitmapData data =
bmp.LockBits(glControl1.ClientRectangle, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
GL.ReadPixels(0, 0, w, h, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0);
bmp.UnlockBits(data);
bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
return bmp;
}
在交换缓冲区后的绘图事件(paint event)中,我进行截屏。问题是所捕获的图像处于绘制之前的状态。这意味着如果我想捕获图像,我需要运行两次绘图事件。我尝试过GL.flush、finish和swapbuffer。有没有人知道如何解决这个问题。还要注意的是,我尝试使用异步方式,但失败了,因为不能从另一个线程访问opentk图像数据。