Search code examples
c++winapimfcgdi

Transparent bounding box of an ellipse


I'm writing some C++ code to draw ellipses. Sometimes these ellipses could be stacked on top of each other in a grouping. When they are stacked on each other, I'd like to have the bounding box of the ellipse be transparent so that I don't see the white corners of the bounding box. See picture below.

enter image description here

Including the SetBkMode or not doesn't seem to make a difference. If I don't do the FillRect, I get a black background on the bounding box.


HBRUSH brush = CreateSolidBrush(RGB(255, 255, 255));
CDC *pDC = CDC::FromHandle(pSprite->hDCMem);
pDC->SetBkMode(TRANSPARENT);
pDC->FillRect(m_SpriteRect, CBrush::FromHandle(brush));
pDC->SelectObject(m_BackBrush);
pDC->Ellipse(m_SpriteRect);
pDC->SetBkMode(OPAQUE);

DeleteObject(brush);

Is there a way to set a transparent background?


Solution

  • If drawing on memory dc, fill the background with a transparent color, then use TransparentBlt to blit the memory dc on to final HDC. Example:

    CDC *pDC = CDC::FromHandle(hDCMem);
    
    //fill the background with transparent color
    COLORREF clr_transparent = RGB(255, 255, 255); //<- randomly selected color
    CBrush brush(clr_transparent);
    pDC->FillRect(m_SpriteRect, &brush);
    
    //any drawing
    auto oldbrush = pDC->SelectObject(m_BackBrush);
    pDC->Ellipse(m_SpriteRect);
    pDC->SelectObject(oldbrush);
    
    //transparent blit
    TransparentBlt(final_hdc, x_dest, y_dest, width, height, 
        hDCMem, 0, 0, m_SpriteRect.right, m_SpriteRect.bottom, clr_transparent);