4

Is there a way to specify how an image is scaled up in an Image element with LayoutTransform set to a ScaleTransform with integer values for ScaleX and ScaleY?

I want to display the scaled image crisply (ie using 'nearest neighbour' scaling), with no blurring. (Imagine how you would want a bitmap editing program to behave when zooming in).

I noticed the protected property VisualBitmapScalingMode on Image, so created a subclass of Image that sets this property to BitmapScalingMode.NearestNeighbor. However, this had no effect.

mackenir
  • 10,801
  • 16
  • 68
  • 100
  • Your subclass won't change how the ScaleTransform works, I think. Have you tried setting the image size manually (width/height) to see if it is crisp? –  May 26 '10 at 12:59
  • Unfortunately not. If I expand the Image by setting Width and Height I get the same result as applying a ScaleTransform. Which makes sense I think, given that either way, it's ultimately the Image that decides how to render itself given a size, and a bitmap. – mackenir May 26 '10 at 13:04
  • Have you gotten any better results with the TransformedBitmap? –  May 26 '10 at 13:14
  • OK if I override OnRender on Image, perhaps I can specify the scaling algorithm to use in the DrawingContext somehow... – mackenir May 26 '10 at 13:36
  • OK, got it working. Although I was setting the value of VisualBitmapScalingMode in the constructor of 'MyImage' (my Image subclass), it was set back to Unspecified by the time OnRender was called. So, I override OnRender, and set it there, then call base.OnRender. Maybe there is some override in the lifecycle of a WPF element where I could set this property once, but job done. – mackenir May 26 '10 at 13:42

2 Answers2

10

You can set the RenderOptions.BitmapScalingMode property in the XAML for the Image control. There's no need to inherit the Image class.

Vimes
  • 10,577
  • 17
  • 66
  • 86
elmo
  • 101
  • 1
  • 2
  • I have a zoom control that changes transform of the child, the image inside the child is blurry even with NearestNeighbor mode. OnRender solution worked (WPF 4.6.2) – Soonts Sep 27 '17 at 20:03
8

I fixed this by overriding OnRender in my Image subclass, and setting the VisualBitmapScalingMode before drawing the image:

class MyImage : System.Windows.Controls.Image
  {
    protected override void OnRender(DrawingContext dc)
    {
      this.VisualBitmapScalingMode = System.Windows.Media.BitmapScalingMode.NearestNeighbor;
      base.OnRender(dc);
    }
  }
mackenir
  • 10,801
  • 16
  • 68
  • 100
  • This works great. I used it for the opposite effect (i.e. Fant method), but got exactly what I wanted. – Gleno Sep 22 '12 at 20:50