【问题标题】:Convert vector <unsigned char> to HBITMAP in C++在 C++ 中将向量 <unsigned char> 转换为 HBITMAP
【发布时间】:2016-05-30 08:44:07
【问题描述】:

我已使用代码here 将PNG 图像加载到BMP 原始矢量std::vector &lt;unsigned char&gt;。现在,我需要将此图像作为背景应用到 WinAPI 窗口,但我不知道如何将其转换为 HBITMAP。也许有人以前做过,或者我可以使用其他格式或变量类型

【问题讨论】:

标签: c++ vector hbitmap


【解决方案1】:

你可以从一开始就使用Gdiplus,打开png文件并获取HBITMAP句柄

//initialize Gdiplus:
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

HBITMAP hbitmap;
HBRUSH hbrush;

Gdiplus::Bitmap *bmp = Gdiplus::Bitmap::FromFile(L"filename.png");
bmp->GetHBITMAP(0, &hbitmap);
hbrush = CreatePatternBrush(hbitmap);

//register classname and assign background brush
WNDCLASSEX wcex;
...
wcex.hbrBackground = hbrush;

CreateWindow...

清理:

DeleteObject(hbrush);
DeleteObject(hbitmap);

delete bmp;

Gdiplus::GdiplusShutdown(gdiplusToken);

您需要包含“gdiplus.h”并链接到“gdiplus.lib”库。默认情况下,头文件应该是可用的。

在 Visual Studio 中,您可以按如下方式链接到 Gdiplus:

#pragma comment( lib, "Gdiplus.lib")


编辑

或在WM_PAINT中使用Gdiplus::Image

Gdiplus::Image *image = Gdiplus::Image::FromFile(L"filename.png");

WM_PAINT 在窗口程序中:

case WM_PAINT:
{
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);

    if (image)
    {
        RECT rc;
        GetClientRect(hwnd, &rc);
        Gdiplus::Graphics g(hdc);
        g.DrawImage(image, Gdiplus::Rect(0, 0, rc.right, rc.bottom));
    }

    EndPaint(hwnd, &ps);
    return 0;
}

【讨论】:

  • 有没有办法让图片的大小和窗口一样?
  • 您可以将背景画笔设置为零,然后在WM_PAINT 中绘画,请参阅编辑。如果你真的需要背景刷那么你必须在WM_SIZE中调整图像大小,使用内存dc调整图像大小等来创建一个新的HBITMAP
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 2020-05-03
  • 2022-01-04
  • 2011-10-19
相关资源
最近更新 更多