Taoist
Taoist

Reputation: 341

Image added to WPF canvas changes size

As part of an application, I have a canvas object <Canvas Name="canvas"/> into which I am trying to insert the components of a clock as follows

// Add Background
Image bg = new Image();
bg.SetValue(Canvas.ZIndexProperty, 0);
bg.Source = new BitmapImage(new Uri("images/background.png", UriKind.Relative));
canvas.Width = bg.Source.Width;
canvas.Height = bg.Source.Height;
canvas.Children.Add(bg);

// Add second hand
Image hand = new Image();
hand.SetValue(Canvas.ZIndexProperty, 10);
hand.Source = new BitmapImage(new Uri("images/hand.png", UriKind.Relative));
canvas.Children.Add(hand);

The first image (bg) appears correctly but the second one (hand) appears to be scaled (original size is 5 x 61 pixels, interrogating image size after creation shows it has become 6.66 x 84.02 display units) (bg original is 130 x 130 pixels and shows as 130.4 in display units)

All the answers to my query that I can find (StackOverflow and Google) suggest DPI setting of image but both my images are 96 DPI (according to Paint) I have tried moving the image declarations into the XAML (not a long term solution) but this makes no difference. I have tried changing the order in which I insert the images with no effect. I have set the canvas width/height explicitly in the XAML - no effect. I have set the size of the image explicitly - again no effect.

Can anybody tell me what is going on?

added: Compiled using .net 4 on windows7 64bit

Resolved: Paint was reporting an incorrect DPI setting for the image. Paint.Net gave me the correct value and by changing this to 96 DPI the problem was resolved

Upvotes: 3

Views: 6757

Answers (2)

Taoist
Taoist

Reputation: 341

Issue resolved: Paint was reporting an incorrect DPI. Using an alternate paint package (Paint.net) showed the DPI was different. Correcting this setting fixed the issue.

Upvotes: 1

Lukasz M
Lukasz M

Reputation: 5723

You haven't set Width and Height for the second image and this had probably caused the issue. You can also try to disable image stretching by adding a line (this should at least not scale the image, even if the control is scaled):

hand.Stretch = Stretch.None;

Update: I've just noticed You've already tried setting the dimensions of the image. Try to set if in the code. I'm currently looking for another possible causes of this problem.

Update II: I see You've found a solution. I'm glad you've made it work :).

Upvotes: 0

Related Questions