Home > Blockchain >  Why does CroppedBitmap result in an invisible image?
Why does CroppedBitmap result in an invisible image?

Time:02-21

I am attempting to use CroppedBitmap to display a portion of a PNG file on a WPF Image element.

As a test, I have the following code:

BitmapImage StandardTilesetImage = new BitmapImage();
StandardTilesetImage.BeginInit();
StandardTilesetImage.CacheOption = BitmapCacheOption.OnLoad;
StandardTilesetImage.UriSource = new Uri(pngFilePath, UriKind.Relative);
StandardTilesetImage.EndInit();

// TestImage is an Image object defined in XAML
TestImage.Source = StandardTilesetImage;

This produces the expected results - the image displays correctly:

enter image description here

For reference the pngFilePath is a string pointing to the absolute location (c:/etc/etc/StandardTilesetIcons.png) which is a 512x512 PNG:

enter image description here

If I modify the code above to clip a part of the PNG (such as drawing the top-left 64x64 area), the TestImage no longer displays anything.

BitmapImage StandardTilesetImage = new BitmapImage();
StandardTilesetImage.BeginInit();
StandardTilesetImage.CacheOption = BitmapCacheOption.OnLoad;
StandardTilesetImage.UriSource = new Uri(pngFilePath, UriKind.Relative);
StandardTilesetImage.EndInit();

CroppedBitmap croppedBitmap = new CroppedBitmap();
croppedBitmap.SourceRect = new Int32Rect(0,0,64, 64);
croppedBitmap.Source = StandardTilesetImage;
TestImage.Source = croppedBitmap;

enter image description here

I would expect to see a portion of the PNG in my TestImage object. Why is nothing showing up?

CodePudding user response:

Just like BitmapImage, CroppedBitmap implements the ISupportInitialize interface, which means that when you create an instance by the default constructor, you have to call the BeginInit() and EndInit() methods before and after setting any of its properties.

Alternatively, use the appropriate constructors with parameters provided by both classes:

BitmapImage standardTilesetImage = new BitmapImage(
    new Uri(pngFilePath, UriKind.RelativeOrAbsolute));

CroppedBitmap croppedBitmap = new CroppedBitmap(
    standardTilesetImage, new Int32Rect(0,0,64, 64));

TestImage.Source = croppedBitmap;
  • Related