Image scaling and its positioning in 0,0 in WPF

I created a BitMapSource from a list of RGBA pixels:

BitmapSource bmp = BitmapSource.Create(imageStrideInPixels, height, 96, 96, PixelFormats.Bgra32, null, imageData, imageStrideInPixels * pixelWidth); 

Then create an image from BitMapSource:

  // create image and set image as source Image BmpImg = new Image(); BmpImg.SetValue(Canvas.ZIndexProperty, 0); BmpImg.Width = imageScaleWidth; BmpImg.Height = imageScaleHeight; BmpImg.Source = bmp; 

Then I add the image to the canvas:

  mycanvas.Width = imageScaleWidth; mycanvas.Height = imageScaleHeight; mycanvas.Children.Clear(); mycanvas.Children.Add(BmpImg); Canvas.SetLeft(BmpImg, 0); // to set position (x,y) Canvas.SetTop(BmpImg, 0); 

The problem is that it does not get scaled to imageScaleWidth and imageScaleHeight, and it is displayed halfway down the canvas.

Notice I was able to do this in Java SWT:

 imageData = imageData.scaledTo(imageScaleWidth, imageScaleHeight); gc.drawImage(imageData, 0, 0); 
+6
source share
3 answers

You can scale the image using ScaleTransform :

 // scale the original bitmap source var transformedBitmap = new TransformedBitmap( bmp, new ScaleTransform( imageScaleWidth / (double) bmp.PixelWidth, imageScaleHeight / (double) bmp.PixelHeight)); // create image and set image as source Image bmpImg = new Image(); bmpImg.SetValue(Canvas.ZIndexProperty, 0); bmpImg.Source = transformedBitmap; mycanvas.Width = imageScaleWidth; mycanvas.Height = imageScaleHeight; mycanvas.Children.Clear(); mycanvas.Children.Add(bmpImg); 

Please note that your image will be placed at offset 0, 0 by default.

+3
source

Instead of this

  mycanvas.Children.Add(BmpImg); 

try it

  mycanvas.Background = new VisualBrush(BmpImg); 

This should display correctly.

+1
source

Are you sure that the image is halfway down the canvas, and not the canvas itself is in the center of its parent? I tested it, and it seems that you can control the position of the canvas by setting the vertical / horizontal alignment on the parent canvas. It also scales correctly when using the code you provided. However, I created BitmapSource in a different way. I used the following code:

 PngBitmapDecoder decoder = new PngBitmapDecoder(new Uri(@"..."), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bmp = decoder.Frames[0]; 
0
source

All Articles