Search code examples
wpfimagexamlcropimagesource

WPF- How Can I Show a Cropped Region of an ImageSource in an <Image> Control?


WPF- How can I show a cropped region of an ImageSource in an control?

I have an ImageSource of a vairable size in pixels. I have a caculated crop rectangle, indicating how much of the image we are actually going to use. I don't want to edit the image data directly, but I want my <Image> control to display only the cropped region of the ImageSource.

Does Microsoft provide a way to automate this?
Any advice is appreciated!


Solution

  • Use a CroppedBitmap.

    Here is an example of its usage:

       <Page.Resources>
          <!-- Define some image resources, for use as the image element source. -->
          <BitmapImage x:Key="masterImage" UriSource="/sampleImages/gecko.jpg" />
          <CroppedBitmap x:Key="croppedImage" 
             Source="{StaticResource masterImage}" SourceRect="30 20 105 50"/>
       </Page.Resources>