C# 使用代码将图像对象添加到 wpf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14336597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:29:11  来源:igfitidea点击:

Adding image objects to wpf with code

c#wpfsimulator

提问by Sam

I'm a rookie at C# and WPF and I'm trying to create a simple car-simulator. Mainly the idea of the simulator is that I have C#-class that creates car-objects that have for example speed variable that can be changed and timer for moving from left to right. I want to do movement with timer and not for example doubleanimation. In WPF I have AddCarButton for adding cars in certain points in Canvas.

我是 C# 和 WPF 的新手,我正在尝试创建一个简单的汽车模拟器。模拟器的主要思想是我有 C# 类,它创建汽车对象,例如可以更改速度变量和从左到右移动的计时器。我想用计时器做运动,而不是例如doubleanimation。在 WPF 中,我有 AddCarButton 用于在 Canvas 的某些点添加汽车。

The problem is I dont know how to add cars to Canvas. This is very frustrating because it doesn't sound like a big thing to do but I feel like I have tried everything and not succeeded.

问题是我不知道如何将汽车添加到 Canvas。这非常令人沮丧,因为这听起来不是一件大事,但我觉得我已经尝试了一切但没有成功。

This is latest attempt with car-class. I have tried using Canvas.Set-methods but failed.

这是汽车级的最新尝试。我曾尝试使用 Canvas.Set-methods 但失败了。

class car
{
    private int speed;

    public car(int s)
    {
        speed = s;
        Bitmap bmp = new Bitmap(
        System.Reflection.Assembly.GetEntryAssembly().
        GetManifestResourceStream("MyProject.Resources.car.png"));
        Graphics g = Graphics.FromImage(bmp);
        //Canvas.SetBottom(g, 0);
        //Canvas.SetLeft(g, 0);
        //Canvas.SetBottom(bmp, 0);
        //Canvas.SetLeft(bmp, 0);
    }
    public void addCar(car c)
    {
        Canvas.SetBottom(c, 0);
        Canvas.SetLeft(c, 0);
    }

回答by zmbq

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

您需要将位图放入Image(而不是Graphics)中,然后需要将图像添加到画布中:

Canvas.Children.Add(image);

回答by someone else

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

如果您在 WPF 上编码,则不应使用Windows 窗体的东西。要处理图像,您使用BitmapSource及其派生类,并以编程方式访问您的资源,您通常使用pack URIs。不过,这不是唯一的方法。

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):

画布的 XAML 代码可能是这样的(这只是一个例子):

<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 Propertieswindow that its Build actionis Resource, don't change this!(some people think it should be Embedded resourcebut that's incorrect).

显然,您需要更改图像资源的名称。顺便说一句,要添加图像,请转到“项目”>“添加现有项目...”并选择您的图像文件,现在您的图像将出现在解决方案资源管理器中(默认情况下,Visual Studio 将图像资源存储在名为“Images”的文件夹中) ,如果您选择它,您将在“属性”窗口中看到它的构建操作Resource不要更改它!(有些人认为它应该是嵌入式资源,但这是不正确的)。

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

如果你没有得到这个new Uri("pack://application:,,,/Images/BlueCar.png", UriKind.Absolute),你应该阅读包 URIs上的这个链接