繪製半透明矩形Gdiplus和GDI性能對比

最近有繪製半透明矩形做遮罩需求,因此在網上找了兩種實現

Gdiplus實現:

void GdipFillAlphaRect(CDC& pDC, CRect& rc, int r, int g, int b, int a)
{
 Gdiplus::Graphics renderer(pDC.GetSafeHdc());
 Gdiplus::Color color(a, r, g, b);

 Gdiplus::Rect rectangle(0, 0, rc.Width(), rc.Height());
 Gdiplus::SolidBrush solidBrush(color);
 renderer.FillRectangle(&solidBrush, rectangle);
}

GDI實現:

void FillAlphaRect(CDC& dc, CRect rect, int r, int g, int b, int a)
{
    CDC cdc;
    cdc.CreateCompatibleDC(&dc);

    CBitmap bitmap, *pOldBitmap;
    bitmap.CreateCompatibleBitmap(&dc, rect.right, rect.bottom);
    CRect src(rect);
    src.OffsetRect(CSize(-rect.left, -rect.top));
    pOldBitmap = cdc.SelectObject(&bitmap);
    cdc.FillSolidRect(src, RGB(r, g, b)); 

    BLENDFUNCTION blendFunc = {0};
    blendFunc.SourceConstantAlpha = a; 
    blendFunc.BlendOp             = AC_SRC_OVER;

    ::AlphaBlend(dc.GetSafeHdc(), rect.left, rect.top, rect.right - rect.left,
                    rect.bottom - rect.top, cdc.GetSafeHdc(), src.left, src.top, src.right - src.left,
                    src.bottom - src.top, blendFunc);

  cdc.SelectObject(pOldBitmap);
}

性能對代碼:

CRect rcClient;
GetClientRect(rcClient);

auto start1 = yasio::highp_clock();
GdipFillAlphaRect(dcMem, rcClient, 27, 29, 45, 255 * 0.2);
auto diff1 = yasio::highp_clock()-  start1;

auto start2 = yasio::highp_clock();
FillAlphaRect(dcMem, rcClient, 27, 29, 45, 255 * 0.2);
auto diff2 = yasio::highp_clock() - start2;

char buf[128];
sprintf(buf, "performance test: gdip=%lld(us), gdi=%lld(us)\n", diff1, diff2);
OutputDebugStringA(buf);

性能打印結果

  • Debug編譯
performance test: gdip=2377(us), gdi=1093(us)
  • Release O2優化:
performance test: gdip=1979(us), gdi=1360(us)
performance test: gdip=3009(us), gdi=1376(us)
performance test: gdip=2141(us), gdi=1244(us)
performance test: gdip=2027(us), gdi=1230(us)
performance test: gdip=2214(us), gdi=1128(us)
performance test: gdip=2155(us), gdi=1100(us)
performance test: gdip=2729(us), gdi=1228(us)
performance test: gdip=1981(us), gdi=1190(us)
performance test: gdip=2067(us), gdi=1198(us)
performance test: gdip=2044(us), gdi=1266(us)
performance test: gdip=2093(us), gdi=1189(us)
performance test: gdip=2133(us), gdi=1166(us)

從結論上看,GDI性能更優

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章