Search code examples
direct2dsharpdx

Clear RenderTarget with transparent color


I'm trying to do some bitmap drawing using SharpDX.Direct2D and WicBitmap as render target.
My code looks like this:

var wicFactory = new ImagingFactory();
var d2dFactory = new SharpDX.Direct2D1.Factory();

var wicBitmap = new SharpDX.WIC.Bitmap(wicFactory, width, height, 
    SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);
var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, 
    new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Unknown), 
    0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

var d2dRenderTarget = new WicRenderTarget(d2dFactory, wicBitmap, renderTargetProperties);

PathGeometry path = new PathGeometry(d2dFactory);
// Create the path figures here ...

SolidColorBrush brush = new SolidColorBrush(d2dRenderTarget, new RawColor4(1, 0, 0, 1));
d2dRenderTarget.BeginDraw();
// The problem is with this line
d2dRenderTarget.Clear(new RawColor4(1, 1, 1, 0));
d2dRenderTarget.DrawGeometry(path, brush, lineWidth);
d2dRenderTarget.EndDraw();

brush.Dispose();

path.Dispose();

bl = wicBitmap.Lock(BitmapLockFlags.Read);
// imageData is a byte[]
Marshal.Copy(bl.Data.DataPointer, imageData, 0, imageData.Length);
bl.Dispose();

d2dRenderTarget.Dispose();
wicBitmap.Dispose();
d2dFactory.Dispose();
wicFactory.Dispose();

File.WriteAllBytes("image.raw", imageData);

What I'm trying to create is an image with transparent background. The Clear method ignores the alpha channel in the clear color if the AlphaMode in PixelFormat is Unknown or Ignore. If I try to set the AlphaMode to Straight or Premultiplied then the WicRenderTarget constructor fails with a COM error: The parameter is incorrect.

What is the correct combination of parameters so that the alpha channel is not ignored in the Clear method?


Solution

  • You have created your WicBitmap with SharpDX.WIC.PixelFormat.Format32bppBGR which does not support an alpha channel. Please use Format32bppPBGRA or similar and set the alpha mode to Premultiplied and it should work.