我试图用绘图操作编写一个直接绘制到屏幕上的类。我的想法是有一个恒定的循环,它渲染图形缓冲区和几个函数,写入图形缓冲区(线条,矩形等)。现在线程存在问题。当它在不同线程的循环中使用时,我无法写入图形缓冲区。但我需要不同的线程来保持恒定的性能/帧速率。我试图创造一个"共享"缓冲区以位图的形式,但性能很糟糕。有谁有任何想法,如何解决这个问题?当前的错误消息是:System.InvalidOperationException @ myGraphics.Clear(Color.Black);
class drawingOnScreen
{
IntPtr desktop; //a pointer to the desktop
Graphics g; //the graphics object
BufferedGraphicsContext currentContext;
BufferedGraphics myBuffer; //graphics buffer
Thread renderThread; //the thread
[DllImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
public void drawLine(Vector2D point1, Vector2D point2, float width, Color color) //Vector2D is basically like Point2D
{
myBuffer.Graphics.DrawLine(new Pen(color, width), point1.x, point1.y, point2.x, point2.y); //trying to draw a line into the buffer
}
public void init() //initializing everything
{
desktop = GetDC(IntPtr.Zero); //setting up for drawing directly to the screen
g = Graphics.FromHdc(desktop); //setting up for drawing directly to the screen
currentContext = BufferedGraphicsManager.Current; //setting up the render buffer
myBuffer = currentContext.Allocate(g, new Rectangle(0, 0, 300, 300)); //setting up the render buffer
renderThread = new Thread(new ThreadStart(renderOp)); //setting up a seperated thread for rendering to avoid lag etc.
renderThread.Start(); //starting the thread
}
void renderOp() //the render thread as a loop
{
while (true)
{
myBuffer.Graphics.Clear(Color.Black); //clear the background
myBuffer.Render(); //render when every drawing operation is finished
}
}
}
感谢任何试图解决我的问题。