How to Crop instead of Clip an Image in Silverlight

The silverlight image element has a Clip property which can be used to clip an image, hiding all but the clipped area.

   <Image Source="Image.jpg" Stretch="None">
               <RectangleGeometry Rect="70,70,50,50"/>

However this works as a mask rather than a crop, leaving the image element at the original size just covering over the unclipped area. For some applications this may what you need but if the image element is in a stack panel (as in the sample below) it would mean the image is surrounded by white space.

Install Microsoft Silverlight

The solution is to use a smaller Writeable Bitmap to copy the image into. In your code create a Writeable Bitmap object the size of the final cropped area (in this case 50×50). Then use the Render method to copy the Image element on to the Writeable Bitmap. When calling the Render method you will have to pass in a translate transform to move the area of the image you wish to crop in to the top left corner. Finally set the source of your image to the new Writeable Bitmap.

  //Create a bitmap of the cropped size
  WriteableBitmap wb = new WriteableBitmap(50, 50 );

  //Create a transform to move the Image to the top left
  TranslateTransform t = new TranslateTransform();
  t.X = -70;
  t.Y = -70;

  //Draw to the Writeable Bitmap
   //Finally set the Image back
   sampleImage.Source = wb;

Download Sample Source Code

Update: As highlighted on this stack overflow question asked by frogbot. If your image has not been added to the canvas you must ensure it has fully loaded before cropping it. This can be done via the ImageOpened event as suggested by keithmahoney.

Tags: , ,

Saturday, August 22nd, 2009 General

5 Comments to How to Crop instead of Clip an Image in Silverlight

  • [...] How to Crop instead of Clip an Image in Silverlight | – view page – cached #RSS Feed » How to Crop instead of Clip an Image in Silverlight Comments Feed Welcome Rendering XAML to a JPEG using Silverlight 3 — From the page [...]

  • Kolya says:


    С наступающим

  • Light says:

    Даже не знаю

    Ссылки как то странно отображаются…

  • Vasya says:


    no more…