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"> <Image.Clip> <RectangleGeometry Rect="70,70,50,50"/> </Image.Clip> </Image>
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.
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 wb.Render(sampleImage,t); wb.Invalidate(); //Finally set the Image back sampleImage.Source = wb;
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.