我在网上找到的库中的以下代码中有原始 RGBA 值的位图。 "svgren.
auto img = svgren::render(*dom, width, height); //uses 96 dpi by default
//At this point the 'width' and 'height' variables were filled with
//the actual width and height of the rendered image.
//Returned 'img' is a std::vector<std::uint32_t> holding array of RGBA values.
我需要知道如何将这张图片放入 CBitmap 中,以便我可以在 MFC Picture 控件中显示它。我可以预先确定它的大小,并且我知道如何在控件中显示位图。我不能做的是将 RGBA 值加载到位图中。有什么想法吗?
最佳答案
CBitmap::CreateBitmap成员函数可以从一 block 内存构造位图。 lpBits 参数需要一个指向 byte 值的指针。将指针传递给 uint32_t
值数组在技术上是未定义的行为(尽管它适用于 Windows 的所有小端实现)。
必须特别注意内存布局。这仅记录了 Windows API 调用 CreateBitmap并且根本不存在于 MFC 文档中:
Each scan line in the rectangle must be word1 aligned (scan lines that are not word aligned must be padded with zeros).
基于内存正确对齐的假设,并且将缓冲区重新解释为指向字节的指针已明确定义,这是一个具有适当资源处理的实现:
CBitmap Chb;
Chb.CreateBitmap(width, height, 1, 32, img.data());
mProjectorWindow.m_picControl.ModifyStyle(0xF, SS_BITMAP, SWP_NOSIZE);
Chb.Attach(mProjectorWindow.m_picControl.SetBitmap(Chb.Detach()));
最后一行代码在 m_picControl
和 Chb
之间交换 GDI 资源的所有权。这确保正确清理以前由 m_picControl
拥有的 GDI 资源,并使 m_picControl
成为新创建的位图的唯一所有者。
1 我相信这个should read dword aligned .
关于c++ - 来自 std::vector<std::uint32_t> 保存数组中原始 RGB 值的 CBitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39479323/