Adding image objects to wpf with code

二次信任 提交于 2019-12-01 09:08:53

If you're coding on WPF you shouldn't use Windows Forms stuff. To work with images you use BitmapSource and its derived classes, and to access your resources programmatically you usually use pack URIs. It's not the only way, though.

Here is a little example that draws some images on a canvas control.

The XAML code for the canvas could be like this (it's just an example):

<Canvas Height="400" HorizontalAlignment="Left" Margin="0" Name="canvas1" VerticalAlignment="Top" Width="400" />

and your main window code...

public partial class MainWindow : Window
{
    BitmapImage carBitmap = new BitmapImage(new Uri("pack://application:,,,/Images/BlueCar.png", UriKind.Absolute));
    Image[] carImg = new Image[5];
    Random rnd = new Random();

    public MainWindow()
    {
        InitializeComponent();
        double maxX = canvas1.Width - carBitmap.Width;
        double maxY = canvas1.Height - carBitmap.Height;
        for (int i = 0; i < carImg.Length; i++)
        {
            carImg[i] = new Image();
            carImg[i].Source = carBitmap;
            carImg[i].Width = carBitmap.Width;
            carImg[i].Height = carBitmap.Height;
            Canvas.SetLeft(carImg[i], rnd.NextDouble() * maxX);
            Canvas.SetTop(carImg[i], rnd.NextDouble() * maxY);
            canvas1.Children.Add(carImg[i]);
        }
    }
}

Obviously you need change the name of your image resource. By the way, to add an image go to Project > Add existing item... and select your image file, now your image will appear in the Solution explorer (by default, Visual Studio stores image resources in a folder called "Images"), if you select it you'll see in the Properties window that its Build action is Resource, don't change this! (some people think it should be Embedded resource but that's incorrect).

If you don't get this new Uri("pack://application:,,,/Images/BlueCar.png", UriKind.Absolute), you should read this link on pack URIs.

You need to put your bitmap in an Image (and not Graphics), and then you need to add the image to the canvas:

Canvas.Children.Add(image);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!