Betty Crokker
Betty Crokker

Reputation: 3373

Can't get Image on Canvas to display image with transparent sections

I have an image (stored as a PNG) that has some transparent areas that I'm loading into a System.Drawing.Bitmap. I've confirmed image.PixelFormat is Format32bppArgb and that the image does indeed have the correct Alpha values (by calling image.Save("img.png")).

I'm then converting the System.Drawing.Bitmap to a BitmapSource by:

BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                ImageLockMode.ReadOnly, image.PixelFormat);
bitmapSource = BitmapSource.Create(image.Width, image.Height,
                    image.HorizontalResolution, image.VerticalResolution,
                    pf, null,
                    bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
image.UnlockBits(bitmapData);

BTW, just to be extra-paranoid, I did a Marshal.Copy() from bitmapData.Scan0 into a byte[] and verified that byte [3] and every 4th byte after that was either 255 or 0 (with 0 and 255 appearing about 50/50 which is correct).

I then take the BitmapSource and add it to an Image in my Canvas:

Image im = new()
{
   Source = bmpSource
};
TheCanvas.Children.Add(im);
Canvas.SetLeft(im, 0);
Canvas.SetTop(im, 0);

The display always shows white where the pixels are transparent, even though the Background of the Canvas is LightGray.

I tried using the helper function:

BitmapSource bs = Imaging.CreateBitmapSourceFromHBitmap(image.GetHbitmap(), IntPtr.Zero,
    new System.Windows.Int32Rect(0, 0, image.Width, image.Height),
    BitmapSizeOptions.FromEmptyOptions());

but that made no difference.

There is no 'Background' property for Image, but it appears that when an Image is placed in a Canvas, it insists on drawing my transparent pixels in white.

Is there a way to have my image displayed properly, with the light-gray pixels of the Canvas showing through where the image is transparent?

Upvotes: 0

Views: 116

Answers (0)

Related Questions