J.Silver
J.Silver

Reputation: 75

Crop an Image in WPF

Give an image:

Image tileSet = new Image();
tileSet.Source = new BitmapImage(new Uri(@".."));

How can i cropt it, defining a rectangle area?

Upvotes: 5

Views: 6119

Answers (2)

Rafael Ventura
Rafael Ventura

Reputation: 314

To build a little on dkozl's answer above,

I found the DPI of the original image to crop and the DPI of the display were creating an "offset" of where I was intending to crop the original image.

The "offset" can be corrected by matching the image Width and Height in pixels with the DPI of the screen, instead of letting the Image element to it's own automatic sizing. You do this by setting the Stretch to None, and the Width & Height of the image as below:

<Image
    x:Name="imageToCrop"
    Stretch="None"
    Width="{Binding Source.PixelWidth,RelativeSource={RelativeSource Self}}"
    Height="{Binding Source.PixelHeight,RelativeSource={RelativeSource Self}}"/>

Upvotes: 0

dkozl
dkozl

Reputation: 33364

You can use CroppedBitmap for that

var fullBitmap = new BitmapImage(new Uri(@".."));
tileSet.Source = new CroppedBitmap(fullBitmap, new Int32Rect(0, 0, 100, 100));

Upvotes: 12

Related Questions