Tae-Sung Shin
Tae-Sung Shin

Reputation: 20633

Showing part of image in display area of WPF image control using ScaleTransform and TranslateTransform

I have a WPF Image control already working in my application. Using ScaleTransform and TranslateTransform, the Image control has zooming and panning functionality working very well.

I was wondering if there is any way to display certain rectangle area of the image source in the Image control using ScaleTransform and TranslateTransform. In order to do that, I think I need to get/set rectangle coordinates of the image source in view port of the Image control. But it seems that I can't find any reference on this.

Upvotes: 2

Views: 3819

Answers (2)

Tae-Sung Shin
Tae-Sung Shin

Reputation: 20633

Lucky for me, the rectangles have all the same size so I could find easily a fixed scale value for ScaleTrensformation such as 5.0 which will fit each rectangle into the view port. Once that determined, I could come up with following function to calculate values for TranslateTransform in terms of coordinate in the image. Hope it may help people in a similar situation.

    public void SetImageCoordinate(double x, double y)
    {

        TransformGroup transformGroup = (TransformGroup)image.RenderTransform;
        ScaleTransform transform = (ScaleTransform)transformGroup.Children[0];

        ImageSource imageSource = image.Source;
        BitmapImage bitmapImage = (BitmapImage) imageSource ;
        //Now since you got the image displayed in Image control. You can easily map the mouse position to the Pixel scale.

        var pixelMousePositionX = -(x ) / bitmapImage.PixelWidth * transform.ScaleX * image.ActualWidth;
        var pixelMousePositionY = -(y) / bitmapImage.PixelHeight * transform.ScaleY * image.ActualHeight;

        //MessageBox.Show("X: " + pixelMousePositionX + "; Y: " + pixelMousePositionY);

        var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
        tt.X = pixelMousePositionX;
        tt.Y = pixelMousePositionY;            
    }

Upvotes: 0

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

I think CroppedBitmap can help you:

<CroppedBitmap x:Key="croppedImage" 
      Source="{StaticResource masterImage}" SourceRect="30 20 105 50"/>

Upvotes: 3

Related Questions