使用WIC将Direct2D绘制的图形保存为文件
从Windows Vista开始引入的WIC(Windows Imaging Component)组件以面向对象的方式处理位图,并且很适合与Direct2D配合使用。
可以将Direct2D绘制的图像使用WIC保存为位图文件。
以下代码演示如何将Direct2D绘制的带有透明背景色的图像保存到png位图文件:
CComPtr<IWICImagingFactory> spWicImagingFactory;
IFR(Direct2DHelper::CreateWICImagingFactory(&spWicImagingFactory));
CComPtr<IWICBitmap> spWicBitmap;
CComPtr<ID2D1RenderTarget> spBitmapRT;
CRect rc;
GetClientRect(&rc);
int width = rc.Width(), height = rc.Height();
IFR(spWicImagingFactory->CreateBitmap(
width,
height,
//GUID_WICPixelFormat32bppBGR,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapCacheOnLoad,
&spWicBitmap));
D2D1_PIXEL_FORMAT pixelFormat = PixelFormat(
DXGI_FORMAT_B8G8R8A8_UNORM,
D2D1_ALPHA_MODE_PREMULTIPLIED);
IFR(m_spD2dFactory->CreateWicBitmapRenderTarget(
spWicBitmap,
RenderTargetProperties(),
//RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT,pixelFormat),
&spBitmapRT));
CComPtr<ID2D1SolidColorBrush> spSolidBrush;
IFR(spBitmapRT->CreateSolidColorBrush(ColorF(ColorF::Pink),&spSolidBrush));
//Drawing...
spBitmapRT->BeginDraw();
spBitmapRT->Clear(ColorF(ColorF::White,0));
D2D1_ELLIPSE ellipse = Ellipse(Point2F(width/2,height/2),width/2-50,height/2-50);
spBitmapRT->FillEllipse(ellipse,spSolidBrush);
spBitmapRT->EndDraw();
CComPtr<IWICStream> spStream;
IFR(spWicImagingFactory->CreateStream(&spStream));
LPCTSTR fileName = _T("output.png");
IFR(spStream->InitializeFromFilename(fileName,GENERIC_WRITE));
CComPtr<IWICBitmapEncoder> spBitmapEncoder;
CComPtr<IWICBitmapFrameEncode> spFrameEncode;
IFR(spWicImagingFactory->CreateEncoder(GUID_ContainerFormatPng,NULL,&spBitmapEncoder));
IFR(spBitmapEncoder->Initialize(spStream,WICBitmapEncoderNoCache));
IFR(spBitmapEncoder->CreateNewFrame(&spFrameEncode,NULL));
IFR(spFrameEncode->Initialize(NULL));
IFR(spFrameEncode->SetSize(width,height));
WICPixelFormatGUID format = GUID_WICPixelFormatDontCare;
IFR(spFrameEncode->SetPixelFormat(&format));
IFR(spFrameEncode->WriteSource(spWicBitmap,NULL));
IFR(spFrameEncode->Commit());
IFR(spBitmapEncoder->Commit());
http://www.cnblogs.com/wdhust/archive/2010/10/16/1852886.html