如何在圆圈内绘制图像?

时间:2018-02-20 20:05:05

标签: c++ mfc freeimage

我有一个MFC应用程序,我需要在圆圈内绘制图像(或将图像裁剪成圆圈)。

我使用FreeImage加载图像,因此使用FreeImage或MFC功能的答案将起作用。

这是我加载图片的方式:

void DrawImage(CDC *pDC, RECT *pRect, const BYTE *pBuffer, int nBufferLength)
{
    FIMEMORY *pfmem = FreeImage_OpenMemory((BYTE*)pBuffer, nBufferLength);
    FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(pfmem);
    FIBITMAP *pdib = FreeImage_LoadFromMemory(fif, pfmem);  

    sz.cx = FreeImage_GetWidth(pdib);
    sz.cy = FreeImage_GetHeight(pdib);

    CRect rc(pRect);

    BITMAPINFO *pbmpi = FreeImage_GetInfo(pdib);
    BYTE *pDibBits = FreeImage_GetBits(pdib);

    ::SetDIBitsToDevice(pDC->GetSafeHdc(), 
                            rc.left, 
                            rc.top, 
                            rc.Width(), 
                            rc.Height(), 
                            0, 
                            0, 
                            0, 
                            rc.Height(), 
                            pDibBits, 
                            pbmpi, 
                            DIB_RGB_COLORS);

    FreeImage_Unload(pdib);
    FreeImage_CloseMemory(pfmem);
}

1 个答案:

答案 0 :(得分:1)

发布我的答案以防有人遇到同样的问题,实际上只是做了@Karthik Krish所写的内容很简单:

//  Get the rect of a circle in the center o the image.
CRect rectMask(pRect);

int cx = rectMask.Width();
int cy = rectMask.Heigth();

if (cx > cy)
{
    rectMask.left += (cx - cy) / 2;
    rectMask.right = rectMask.left + cy;
}
else
{
    rectMask.top += (cy - cx) / 2;
    rectMask.bottom = rectMask.top + cx;
}

HRGN hRegiaoClip = NULL;

//  Create a region for the circle
hRegiaoClip = ::CreateEllipticRgnIndirect(&rectMask);

//  Select circle in the Device context.
::SelectClipRgn(pDC->GetSafeHdc(), hRegiaoClip);

//  Call function to draw the image (the one in the question).
DrawImage(pDC, pRect, pImgBytes, pSerial->GetImageBufferSize(), TRUE);

//  Clean up
::SelectClipRgn(pDC->GetSafeHdc(), NULL);
::DeleteObject(hRegiaoClip);