How does Silverlight Image Clipping work?

I have a very large image that I would like to use for sprites (Γ  la css image sprites ).

I have the code below:

<Image x:Name="testImage" Width="24" Height="12" Source="../Resources/Images/sprites.png"> <Image.Clip> <RectangleGeometry Rect="258,10632,24,12" /> </Image.Clip> </Image> 

This will copy the original image at 24x12 at a relative position of 258, 10632 in the original image.

The problem is that I want the cropped image to show at 0,0 in testImage, while it shows it at 258, 10632. It uses geometry as a guide for cutting, as well as a layout guide.

Does anyone know how to do this? if at all.

Conclusion: There seems to be no good way to do this at this time, the Graeme solution seems the closest to achieving this with Silverlight 2.0.

However, if anyone knows how best to do this, answer with an answer.

+2
geometry silverlight
source share
5 answers

It turns out that this can be done.

 <Rectangle x:Name="myRect" Width="28" Height="12" /> ImageBrush imageBrush = new ImageBrush(); imageBrush.ImageSource = //Load in image source imageBrush.Stretch = Stretch.None; imageBrush.AlignmentX = AlignmentX.Left; imageBrush.AlignmentY = AlignmentY.Top; TranslateTransform offsetTransform = new TranslateTransform(); offsetTransform.X = -258; offsetTransform.Y = -10632; imageBrush.Transform = offsetTransform; 
+3
source share

Assuming you're on canvas

 <Image x:Name="testImage" Width="24" Height="12" Canvas.Left="-258" Canvas.Top="-10632" Source="../Resources/Images/sprites.png"> <Image.Clip> <RectangleGeometry Rect="258,10632,24,12" /> </Image.Clip> 

With WPF, you would use CroppedBitmap, but unfortunately this does not exist in Silverlight.

<Edit>

With further experimentation, a solution without using a canvas:

 <Image x:Name="testImage" Width="24" Height="12" Source="../Resources/Images/sprites.png"> <Image.Clip> <RectangleGeometry Rect="258,10632,24,12" /> </Image.Clip> <Image.RenderTransform> <TranslateTransform X="-258" Y="10632"/> </Image.RenderTransform> </Image> 

He does the same as the canvas, a little more neat.

+1
source share

The Silverlight 3.0 Bitmap API allows you to capture a clip from your sprite image.

See this post on How to crop instead of a clip in silverlight

+1
source share

Why is this at all, the whole point of css image sprites is to improve load time by making one request instead of many. But you can achieve the same by simply placing all your images in xap (or xap) and loading them in a single request.

+1
source share

This is perfectly doable β€” the solution is to use negative fields, not transforms. Just set the top and top negative margins to eat the offset of the top / left clip (258,10632 in your example). Negative margins are also needed on the right and bottom to eat the rest of the original image; formula for the right edge:

-1 * (width_of_source - x_coord_of_clip - width_of_clip_region)

+1
source share

All Articles