Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling an Image and positioning it at 0,0 in WPF

I have created BitMapSource from a list of RGBA pixels:

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

I then create an image from the 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;

I then 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 is not getting scaled to imageScaleWidth and imageScaleHeight, and it is being displayed half way down the canvas.

Note, I was able to do this in Java SWT by:

imageData = imageData.scaledTo(imageScaleWidth, imageScaleHeight);
gc.drawImage(imageData, 0, 0); 
like image 957
Robben_Ford_Fan_boy Avatar asked Jun 24 '16 13:06

Robben_Ford_Fan_boy


2 Answers

You can scale your image using a 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);

Note that your image will be positioned at offset 0, 0 by default.

like image 155
Dirk Vollmar Avatar answered Sep 30 '22 12:09

Dirk Vollmar


Instead of this

            mycanvas.Children.Add(BmpImg);

Try this

       mycanvas.Background = new VisualBrush(BmpImg);

This should render properly.

like image 37
adminSoftDK Avatar answered Sep 30 '22 13:09

adminSoftDK