最近有绘制半透明矩形做遮罩需求,因此在网上找了两种实现
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);
性能打印结果
performance test: gdip=2377(us), gdi=1093(us)
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性能更优