avivr
avivr

Reputation: 2593

WPF - How to zoom specific area in an image

I want to show a specific area of an image in my WPF control. Let's say the original image dimensions are 600x400 and I'm trying to show a rectangle inside that image, positioned on X=420,Y=330 with width=60, height=40.

Sample image

So I tried to use ScaleTransform and calculate the scale factor as 10, and the RenderTransformOrigin to 0.75, 0.85.

But when I view the control I don't get the image I expected. (only the red rectangle).

The is the code:

<Grid>
      <Button Width="600" Height="400">
         <Button.Template>
            <ControlTemplate>
              <Grid ClipToBounds="True">
                     <Image Source="c:\temp\sample.bmp" Stretch="Uniform" RenderTransformOrigin="0.75, 0.85">
                        <Image.RenderTransform>
                              <ScaleTransform ScaleX="10" ScaleY="10" />
                       </Image.RenderTransform>
                     </Image>               
                  </Grid>
            </ControlTemplate>
         </Button.Template>
      </Button>
   </Grid>

That the result: Result control

Upvotes: 1

Views: 1714

Answers (1)

Clemens
Clemens

Reputation: 128013

You could use a CroppedBitmap:

<Image>
    <Image.Source>
        <CroppedBitmap Source="c:\temp\sample.bmp" SourceRect="420,330,60,40"/>
    </Image.Source>
</Image>

Or you use an ImageBrush with an appropriate Viewbox:

<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="c:\temp\sample.bmp"
                    ViewboxUnits="Absolute" Viewbox="420,330,60,40"/>
    </Grid.Background>
</Grid>

Upvotes: 2

Related Questions