C++根据png图绘制异性窗口

void TrimWindowRegion(HWND hWnd, Gdiplus::Bitmap& rBmp)
{
	if ( rBmp.GetWidth() > 0 && rBmp.GetHeight() > 0 )
	{
		Gdiplus::Color colr;
		HRGN hRgn = CreateRectRgn(0, 0, rBmp.GetWidth(), rBmp.GetHeight());
		for (int nWidth=0; nWidth <= rBmp.GetWidth(); ++nWidth)
		{
			for (int nHeight=0; nHeight <= rBmp.GetHeight(); ++nHeight)
			{
				if ( rBmp.GetPixel(nWidth, nHeight, &colr) == Gdiplus::Status::Ok )
				{
					//当前像素为透明
					if ( colr.GetA() == 0 )
					{
						HRGN hTmpRgn = CreateRectRgn(nWidth, nHeight, nWidth+1, nHeight+1);
						//扣除这个像素点
						int ret = CombineRgn(hRgn, hRgn, hTmpRgn, RGN_XOR);
						DeleteObject(hTmpRgn);
					}
				}
			}
		}

		if ( hRgn )
		{
			SetWindowRgn(hWnd, hRgn, FALSE);

			DeleteObject(hRgn);
		}
	}
}


说明:

HWND hWnd为当前窗口句柄

Gdiplus::Bitmap& rBmp为使用gdi+加载的png图

如果加载的图不为png图,没有Alpha通道,而是设置某种颜色为透明色,则可在判断透明处(if ( colr.GetA() == 0 ))改用判断颜色,进行抠图


调用:

在创建窗口后调用

	SetWindowLongPtr(m_p_iw->hWnd, GWLP_USERDATA, (LONG_PTR) this);

	TrimWindowRegion(GetHwnd(), *m_p_iw->pPaintBmp);

	SetWindowPos(GetHwnd(), NULL, 0, 0, m_p_iw->pPaintBmp->GetWidth(), m_p_iw->pPaintBmp->GetHeight(), SWP_NOZORDER | SWP_NOMOVE);


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将片设置为窗口背景,需要经过以下步骤: 1. 使用Windows API创建窗口。 2. 加载片,可以使用GDI+库或者其他片处理库。 3. 将绘制窗口的背景上,可以使用Windows API的WM_PAINT消息,或者其他绘函数。 下面是一个简单的示例代码,可以将名为"image.bmp"的片设置为窗口背景: ``` #include <Windows.h> #include <gdiplus.h> #pragma comment(lib, "gdiplus.lib") LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // 加载片 Gdiplus::Bitmap* bmp = Gdiplus::Bitmap::FromFile(L"image.bmp"); if (bmp != NULL) { // 绘制片 Gdiplus::Graphics graphics(hdc); graphics.DrawImage(bmp, 0, 0); delete bmp; } EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // 注册窗口类 WNDCLASS wc = { 0 }; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszClassName = L"MyWindowClass"; RegisterClass(&wc); // 创建窗口 HWND hWnd = CreateWindow(L"MyWindowClass", L"Window Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, hInstance, NULL); if (hWnd == NULL) return 0; // 显示窗口 ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); // 消息循环 MSG msg = { 0 }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值