Maxwell
Maxwell

Reputation: 303

CroppedImage from BitmapImage

I am trying to display a fixed part of an Image in an Image control. The Source is a BitmapImage either from the disk or a web resource and is loaded asynchronously.

I tried using CroppedImage

<UserControl.Resources>
    <CroppedBitmap x:Key="croppedImage" Source="{Binding Image}" SourceRect="20 46 273 202"/>
</UserControl.Resources>
...
<Image x:Name="TemplateImage" Height="202" Width="273" HorizontalAlignment="Left" Source="{StaticResource croppedImage}"/>

This produces an XamlParseException when trying to create the CroppedBitmap.
I also tried this in the code behind (C#)

new CroppedBitmap(Image, new System.Windows.Int32Rect(20, 46, 273, 202))

giving me an ArgumentException when loading from a web resource, stating that the value is out of the expected range. I suppose this is due to the Image not yet beeing loaded, thus having no size.

Is there a way to accomplish this (not necessarily with a CroppedImage), without having to preload the image?

btw: Giving the BitmapImage directly as source to the Image control works fine, but of course this does not do the cropping.

Upvotes: 2

Views: 1194

Answers (2)

Clemens
Clemens

Reputation: 128147

Instead of the Image control you may use a Rectangle with an ImageBrush Fill, and set the Viewbox as needed:

<UserControl.Resources>
    <ImageBrush x:Key="croppedImage" ImageSource="{Binding Image}"
                ViewboxUnits="Absolute" Viewbox="20,46,273,202"/>
</UserControl.Resources>
...
<Rectangle Height="202" Width="273" Fill="{StaticResource croppedImage}"/>

Upvotes: 2

baueric
baueric

Reputation: 386

What you could do is create a dummy source that is just a blank bitmap:

var src = BitmapImage.Create(
                        500, // set to be big enough so it can be cropped
                        500, // set to be big enough so it can be cropped
                        96,
                        96,
                        System.Windows.Media.PixelFormats.Indexed1,
                        new BitmapPalette(new List<System.Windows.Media.Color> { System.Windows.Media.Colors.Transparent }),
                        new byte[] { 0, 0, 0, 0 },
                        1);

Set your Image property that is bound as the source of the CroppedBitmap to this dummy. Then when the actual image loads you just replace this dummy with the real one. The binding system should take care of updating it when you set the Image property to the new source.

Upvotes: 0

Related Questions