C# 从相对路径加载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13078613/
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 01:33:36  来源:igfitidea点击:

Loading images from a relative path

c#wpfresx

提问by Sean Allred

I'm making a BlackHyman game for a project in college (semester-long) and I've hit a road block that I can't seem to get over.

我正在为大学(一学期)的一个项目制作二十一点游戏,但我遇到了一个似乎无法克服的障碍。

I'm trying to load the card images so they can be displayed onscreen, but I've been having verylittle luck in doing so. I've got absolute references down; I can load from those, but any attempt to load from a relative path fails. The project must be standalone; I can't instruct my professor to copy these images onto the root.

我想这样他们就可以被显示在屏幕上加载卡图像,但我一直有非常这样做一点运气。我有绝对的参考资料;我可以从这些加载,但任何从相对路径加载的尝试都会失败。项目必须是独立的;我无法指示我的教授将这些图像复制到根目录上。

#if FROMDISK
        Uri myUri = new Uri(@"C:\cards\" + getFilename(r, s, "png"), UriKind.Absolute);
        PngBitmapDecoder decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        BitmapSource bmp = decoder2.Frames[0];
#else
        System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
        Stream myStream = myAssembly.GetManifestResourceStream("BlackHyman." + getFilename(r, s, "png"));
        BitmapImage bmp = new BitmapImage();
        bmp.StreamSource = myStream;
#endif
        // Draw the Image
        im.Source = bmp;
        im.Stretch = Stretch.Uniform;
        im.Width = CARD_WIDTH;

(Context)

(语境)

采纳答案by Johan Larsson

You can use:

您可以使用:

Uri uri = new Uri(@"FolderName\FileName.png",UriKind.Relative);
PngBitmapDecoder decoder2 = new PngBitmapDecoder(uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

Remember to set the properties for the image file to (otherwise the compiler will skip them) you can look the bin/debug folder after build and verify that the file is where it should be:

请记住将图像文件的属性设置为(否则编译器将跳过它们),您可以在构建后查看 bin/debug 文件夹并验证文件是否位于应有的位置:

  • Build action: content
  • Copy to output directory: Copy always
  • 构建动作:内容
  • 复制到输出目录:始终复制

Another option is to make the file an embedded resourcethen you can access it like this:

另一种选择是使文件成为嵌入式资源,然后您可以像这样访问它:

Bitmap bitmap = Properties.Resources.FileName;

回答by Clone

The way I'm loading some background images that are imported in the project's resources:

我加载一些在项目资源中导入的背景图像的方式:

this.staticBg.Source = new BitmapImage(
    new Uri(@"/Project;component/Images/" + ((App)App.Current).bgImage
                                          + ".jpg", UriKind.Relative));

Where "Project" is project name. So basically you should add images to resources and call them with relative uri.

其中“项目”是项目名称。所以基本上你应该向资源添加图像并使用相对 uri 调用它们。

回答by Joe

I like to declare images as resources in my XAML. I will assume that you can still play around with the code structure at this point, and hopefully there aren't too many new concepts for you. Here's how I do it:

我喜欢在 XAML 中将图像声明为资源。我假设此时您仍然可以使用代码结构,希望不会有太多新概念。这是我的方法:

Start y creating a folder in your project called "Images". Add the images of your cards by drag and dropping them onto the folder in Visual Studio. Make sure their "Build Action" is set to Resource.

开始在您的项目中创建一个名为“Images”的文件夹。通过将卡片的图像拖放到 Visual Studio 中的文件夹中来添加它们。确保他们的“构建操作”设置为资源。

Create a new "Resource Dictionary" by pressing CTRL-SHIFT-A. Name it CardImages.xaml.

按 CTRL-SHIFT-A 创建一个新的“资源字典”。将其命名为 CardImages.xaml。

Link this file in App.xaml like this (showing how to link multiple XAML files at once, but for this of course remove the "AnyDictionary" line!)

像这样在 App.xaml 中链接这个文件(展示如何一次链接多个 XAML 文件,但为此当然删除“AnyDictionary”行!)

App.XAML:

应用程序.XAML:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Controls/CardImages.xaml" />
            <ResourceDictionary Source="Controls/AnyDictionaryYouWant.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Add this code to CardImages.xaml. Rename "MyBlackHymanAssembly" to the assembly name of your proejct.

将此代码添加到 CardImages.xaml。将“MyBlackHymanAssembly”重命名为您项目的程序集名称。

<Style TargetType="Image">
    <Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality" />
</Style>

<DataTemplate x:Key="Spade1">
    <Image Source="MyBlackHymanAssembly;component/Images/Spade1.png" />
</DataTemplate>

<DataTemplate x:Key="Spade2">
    <Image Source="MyBlackHymanAssembly;component/Images/Spade2.png" />
</DataTemplate>

Then, you can locate them in your code like this:

然后,您可以像这样在代码中找到它们:

Label label = new Label();
label.ContentTemplate = (DataTemplate)label.FindResource("Spade1");

This will get you a WPF Label object that should show your card. This technique works with anything that supports ContentTemplate. You can then add your Label to a grid on your UI, I'm not sure how you display your cards on screen.

这将为您提供一个应显示您的卡片的 WPF 标签对象。此技术适用于支持 ContentTemplate 的任何内容。然后您可以将您的标签添加到您 UI 上的网格中,我不确定您如何在屏幕上显示您的卡片。

For a blackHyman application, I would probably create a UserControl called "Card" in order to be able to generate it kind of like this. This encapsulates the "card generation" logic into its own Control so the rest of the code can just focus on dealing the cards.

对于二十一点应用程序,我可能会创建一个名为“Card”的 UserControl,以便能够像这样生成它。这将“卡片生成”逻辑封装到它自己的 Control 中,因此其余代码可以只专注于处理卡片。

XAML:

XAML:

<myControls:CardImage Kind="Spades" Digit="1" />

Or like this in c#:

或者像在 c# 中这样:

CardImage aCard = new CardImage();
aCard.Kind = CardImage.Kinds.Spades; //enum
aCard.Digit = 1;