在WPF应用程序中加载图像 [英] Load Images in WPF application

查看:134
本文介绍了在WPF应用程序中加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对WPF并不熟悉,我感到很困惑。

I am not familiar with WPF, and I just feel quite confusing.

我正在尝试创建一个小型电脑游戏,并且有一些我想要显示的元素动态。我使用Image类并将图像添加到画布。但我不确定这是不是一个好习惯。我觉得在画布上添加控件似乎有点连线。而且我对性能有点担心,因为我可能需要很多图像。

I am trying to create a little computer game, and there are elements I want to display dynamically. I use Image class and add the images to a canvas. But I'm not sure whether it's a good practice. I feel that adding controls to canvas seem to be a little wired. And I'm a little concerned about the performance, because I may need many images.

真正的问题是,我无法加载图像文件中的图像。我在这样的教科书中看到了一个例子(XMAL):

The real problem is, I can't load the images from the image files. I see an example in a text book like this (XMAL):

<Image Panel.ZIndex="0" Margin="0,0,0,0" Name ="image1">
    <Image.Source>
        <BitmapImage UriSource="Bell.gif" />
    </Image.Source>
</Image>

将Bell.gif添加到项目中的地方。

Where Bell.gif is added into the project.

我试图在代码中复制它以创建图像。

And I tried to copy this in code to create an image.

new Image { Source = new BitmapImage(new Uri("Blockade.bmp"))}

但我得到了无效的Uri异常。在互联网上进行一些搜索之后,我发现动态加载资源似乎很困难。我可以动态加载添加到项目中的文件吗?

But I got invalid Uri exception. After some search in the Internet, I found that loading resources dynamically seems to be difficult. Can I load the files added to the project dynamically?

如果我使用绝对路径,则可以。但我不能指望每台计算机都会将文件放在同一个位置。我可以使用相对路径吗?

If I use absolute path then it's OK. But I can't expect every computer will put the files in the same location. Can I use relative path?

我试过

new Image { Source = new BitmapImage(new Uri(@"Pictures\Blank Land.bmp", UriKind.Relative)) }

但它不起作用。 (图片为空白)

But it doesn't work. (The image is blank)

谢谢。

我删除了代码。我刚刚在MSDN中找到了WPF中的包URI中的解决方案。
我可以对本地程序集中的资源使用pack:// application:,,, / Blockade.bmp(绝对)或/Blockade.bmp(相对)。
(我最初没有使用'/')
pack:// application:,,, / ReferencedAssembly; component / File.xaml用于引用程序集。 (我猜答案的问题在于缺少权威部分)

I deleted the code. I just found the solution in "Pack URIs in WPF" in MSDN. I can either use "pack://application:,,,/Blockade.bmp" (absolute) or "/Blockade.bmp" (Relative) for a resource in the local assembly. (I didn't use '/' at first) "pack://application:,,,/ReferencedAssembly;component/File.xaml" is for referenced assembly. (I guess the problem with the answer is that the authority part is missing)

推荐答案

以下作品:

new BitmapImage(new Uri("/MyProject;component/Resources/next.png", UriKind.Relative));

只需将MyProject替换为项目名称,然后调整图像的路径。

Just replace "MyProject" with the name of your project, and adjust the path to your image.

确保将图像添加到项目中,并将BuildAction设置为Resource。

Make sure the image is added to the project with the "BuildAction" set to "Resource".

这篇关于在WPF应用程序中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆