简体   繁体   中英

Image displays differently in XAML vs. C#

I want to show an image in a Grid

Only the image shows when I use this XAML:

<Image Source="/Assets/O.png"
       Grid.Column="6"
       Grid.Row="5"/>

In C# it shows the picture with a border outside:

Image img = new Image();
BitmapImage bi = new BitmapImage();
bi.UriSource = new Uri("/Assets/O.png", UriKind.Relative);
img.Stretch = Stretch.Fill;
img.Source = bi;
Grid.SetColumn(img, 6);
Grid.SetRow(img, 7);
gridGameBoard.Children.Add(img);

Image img1 = new Image();
img1.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Assets/X.png", UriKind.Relative));
Grid.SetColumn(img1, 4);
Grid.SetRow(img1, 4);
gridGameBoard.Children.Add(img1);

I tried googling to find any differences between BitmapImage and other Image types but was unsuccessful.

The problem is the Stretch property of your Image . In XAML, you do not define it, so a default value of Uniform is used. In C# code you have img.Stretch = Stretch.Fill;

My guess is that the border is in the image, but in the C# code with Fill the image is scaled down, the XAML variant with Uniform scales up the image and centers it so the border is not visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM