Scaling an Image and positioning it at 0,0 in WPF
You can scale your image using a ScaleTransform
:
// scale the original bitmap sourcevar transformedBitmap = new TransformedBitmap( bmp, new ScaleTransform( imageScaleWidth / (double) bmp.PixelWidth, imageScaleHeight / (double) bmp.PixelHeight));// create image and set image as sourceImage bmpImg = new Image();bmpImg.SetValue(Canvas.ZIndexProperty, 0);bmpImg.Source = transformedBitmap;mycanvas.Width = imageScaleWidth;mycanvas.Height = imageScaleHeight;mycanvas.Children.Clear();mycanvas.Children.Add(bmpImg);
Note that your image will be positioned at offset 0, 0 by default.
Instead of this
mycanvas.Children.Add(BmpImg);
Try this
mycanvas.Background = new VisualBrush(BmpImg);
This should render properly.
Are you sure the image is half way down the canvas and not the canvas itself is centered in its parent? I tested it and it appears that you can control the canvas position by setting vertical/horizontal alignment on canvas' parent. And also it scales properly when using the code you provided. However I created a 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];