1

im trying to make a window which contain "browse" button to load image file and a button "+" to zoom in the image. Browse button and its open dialog successfully loads the image into Image aka . When I press "+" button, it doesnot zoom in the loaded image but blurs it. Whats wrong?

The original loaded image is named as OriginalSizedImage. The zoomedIn image is named as

private void ZoomInButton_Click(object sender, RoutedEventArgs e)
        {
            BitmapImage newZoomedInImage = new BitmapImage();
            newZoomedInImage.BeginInit();
            newZoomedInImage.DecodePixelWidth = originalSizedImage.DecodePixelWidth + 20 ;
            newZoomedInImage.DecodePixelHeight = originalSizedImage.DecodePixelHeight + 20;
            newZoomedInImage.UriSource = originalSizedImage.UriSource;
            newZoomedInImage.EndInit();
            imageView.Source = newZoomedInImage ;
        }
Sumaira Samar
  • 73
  • 1
  • 1
  • 10
  • Besides that setting DecodePixelWidth/Height won't crop an image, it makes no sense to create new BitmapImage instances all the time. Better just set an appropriate RenderTransform on the Image element that shows the BitmapImage. Use e.g. a ScaleTransform. Otherwise just use a CroppedBitmap, e.g. like here: https://stackoverflow.com/a/29768984/1136211 – Clemens Jan 27 '19 at 15:43
  • Possible duplicate of [Zoom Cropped pixels in a user control](https://stackoverflow.com/questions/28740086/zoom-cropped-pixels-in-a-user-control) – Sebastian L Jan 27 '19 at 15:45
  • that thread is difficult. I was unable to understand it – Sumaira Samar Jan 27 '19 at 16:10

1 Answers1

4

It is unnecessary and inefficient to create a new BitmapImage each time you change the zoom factor.

Better put the Image element in a parent element that clips it

<Grid ClipToBounds="True">
    <Image x:Name="imageView" RenderTransformOrigin="0.5,0.5">
        <Image.RenderTransform>
            <ScaleTransform/>
        </Image.RenderTransform>
    </Image>            
</Grid>

and then modify the ScaleTransform that is assigned to its RenderTransform (and perhaps also its RenderTransformOrigin):

private void ZoomInButtonClick(object sender, RoutedEventArgs e)
{
    var transform = (ScaleTransform)imageView.RenderTransform;
    transform.ScaleX *= 1.1;
    transform.ScaleY *= 1.1;
}

private void ZoomOutButtonClick(object sender, RoutedEventArgs e)
{
    var transform = (ScaleTransform)imageView.RenderTransform;
    transform.ScaleX /= 1.1;
    transform.ScaleY /= 1.1;
}
Clemens
  • 123,504
  • 12
  • 155
  • 268