A red rectangle drawn on 2D texture disappears rig

2019-03-04 06:41发布

问题:

following my another question, I have provided the code that draws the rectangle as follows:

void COpenGLControl::DrawRectangleOnTopOfTexture()
{
wglMakeCurrent(hdc, hrc);
glPushAttrib(GL_ENABLE_BIT|GL_CURRENT_BIT);
glDisable(target);
glColor3f(1.0f,0.0f,0.0f);
glBegin(GL_LINE_LOOP);
   glVertex2f(RectangleToDraw.at(0),RectangleToDraw.at(1));
   glVertex2f(RectangleToDraw.at(0),RectangleToDraw.at(3));
   glVertex2f(RectangleToDraw.at(2),RectangleToDraw.at(3));
   glVertex2f(RectangleToDraw.at(2),RectangleToDraw.at(1));
glEnd();
glPopAttrib();
SwapBuffers(hdc);
wglMakeCurrent(NULL, NULL);
}  

void COpenGLControl::OnDraw(CDC *pDC)
{
// TODO: Camera controls
wglMakeCurrent(hdc,hrc);
glLoadIdentity();
gluLookAt(0,0,1,0,0,0,0,1,0);
glTranslatef(m_fPosX, m_fPosY, 0.0f);
glScalef(m_fZoom,m_fZoom,1.0);
setViewRectangle();
if (WantToDrawRectangle)
    DrawRectangleOnTopOfTexture();
wglMakeCurrent(NULL, NULL);
}  

the problem here is:
the red rectangle disappears right after the OnDraw returns. I mean for example when you do a fixed zoom in or fixed zoom out by pressing a button on the dialog, a red rectangle flashes and then immediately disappears.
Or when you make the OnDraw run constanly ( for example you pan with high speed ), you get something like this:
surely red rectangles are deleted(disappeared) after a short time but this track of red rectangles is shown for a short period of time?

How can I make the current red rectangle be rendered on the texture until the next call of OnDraw?
Also how can I make the current red rectangle be deleted as soon as the next call of OnDraw occurs?

If the second question is hard to answer, no problem please at least answer the first. Obviously if the user does panning with a normal speed this track of rectangles won't be shown.

回答1:

I guess your issue is related to double buffering.

Some devices do not delete the content of the back buffer when it is being swapped. My suggestion would be to clear the screen explicitly (glClear) before you start rendering into the new buffer. This should handle the issue related to multiple red rectangles.

Secondly I am not sure if there are more than necessary buffer swaps happening in your code. Please check if there other explicit or implicit calls to Swap Buffer which might result in the wrong buffer being displayed. (The final buffer displayed might not be the buffer in which you drew the rectangle).