我需要将 Direct2D ID2D1HwndRenderTarget 转换为 ID2D1Bitmap。 但是,我遇到 CopyFromRenderTarget 错误。 “错误:E_INVALIDARG 一个或多个参数无效。”
可能是什么问题?
使用 Direct2D 1.0(包括 d2d1.h)
HRESULT hr;
ID2D1Factory* factory;
hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &factory);
ID2D1HwndRenderTarget* target;
D2D1_RENDER_TARGET_PROPERTIES prop{ D2D1::RenderTargetProperties() };
factory->CreateHwndRenderTarget(prop,D2D1::HwndRenderTargetProperties(hwnd,
D2D1::SizeU(static_cast<UINT>(width), static_cast<UINT>(height))), target);
// ID2D1HwndRenderTarget* target
HRESULT hr;
D2D1_SIZE_F size = target->GetSize();
UINT width = static_cast< UINT >( size.width );
UINT height = static_cast< UINT >( size.height );
D2D1_SIZE_U px_size = target->GetPixelSize();
D2D1_BITMAP_PROPERTIES props;
bitmapProperties.pixelFormat = D2D1::PixelFormat( DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED );
bitmapProperties.dpiX = 96.0f;
bitmapProperties.dpiY = 96.0f;
ID2D1Bitmap* src_bitmap;
hr = target->CreateBitmap( px_size, NULL, 0, &props, &src_bitmap );
// Copy the contents of the current drawing target to a bitmap
D2D1_POINT_2U destPoint = D2D1::Point2U( 0, 0 );
D2D1_RECT_U srcRect = D2D1::RectU( 0, 0, px_size.width, px_size.height );
// Error: E_INVALIDARG One or more arguments are invalid.
hr = src_bitmap->CopyFromRenderTarget( &destPoint, target, &srcRect );
HWND Direct2D 渲染目标支持各种像素格式。当您像您一样创建它时(传递
D2D1::RenderTargetProperties()
),您隐式地使用了 DXGI_FORMAT_B8G8R8A8_UNORM
+ D2D1_ALPHA_MODE_IGNORE
参数。
因此,您可以更改创建渲染目标的方式(可以使用
D2D1_ALPHA_MODE_PREMULTIPLIED
)并且不更改位图的像素格式,或者将位图的像素格式更改为 D2D1_ALPHA_MODE_IGNORE
。
但最好的方法是复制渲染目标的像素格式,如下所示:
D2D1_BITMAP_PROPERTIES bitmapProperties{}; // use 0 for dpi means auto-adapt
bitmapProperties.pixelFormat = pDemoApp->m_pRenderTarget->GetPixelFormat();