【问题标题】:Xamarin Forms Display image from Embedded resource using XAMLXamarin Forms 使用 XAML 显示来自嵌入式资源的图像
【发布时间】:2019-03-18 12:53:09
【问题描述】:

我正在尝试在共享项目资源中显示和嵌入图像(如 Microsoft 文档中的 here 所述)。

我创建了 ImageResourceExtension,项目可以编译,但是启动项目时出现以下错误:

无法从 程序集'Xamarin.Forms.Core,版本=2.0.0.0

这是我的代码:

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App1"
             x:Class="App1.MainPage">

    <StackLayout>

        <Image x:Name="imgTest" Source="{local:ImageResource img.jpg}" />

    </StackLayout>

</ContentPage>

EmbeddedImage.cs

namespace App1
{
    [ContentProperty(nameof(Source))]
    public class ImageResourceExtension : IMarkupExtension
    {
        public string Source { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Source == null)
                return null;

            // Do your translation lookup here, using whatever method you require
            var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);

            return imageSource;
        }
    }
}

【问题讨论】:

  • 你能提供你的代码吗?您确定问题与图像有关吗?
  • 如果我删除 我没有得到错误。所以很确定它是相关的:) 我将代码添加到我的初始帖子中。谢谢
  • 你能提供你的图片的路径吗?您的图片保存在共享项目中的什么位置?

标签: xamarin xamarin.forms


【解决方案1】:

你可以试试这个,它对我有用

xyz.xaml.cs

imgName.Source = ImageSource.FromResource("ProjectName.Images.backicon.png");

xyz.xaml

<Image x:Name="imgName" />

希望这段代码对你有帮助!!

【讨论】:

    【解决方案2】:

    不知道答案是否对您仍然有效,但我通常在我的解决方案之外有一个 Assets 文件夹,其中包含 Android 特定文件夹(drawables)、iOS 特定文件夹(带有@2x 和 @3x 的资源)和一个 Common 文件夹共享图片。

    在我的解决方案中,我将这些文件作为链接添加到它们应该关联的文件夹中。在资源/Drawable 中的 Android 和资源中的 iOS 上。在这种情况下,通用文件可以在两个平台之间共享,而无需物理复制它们。

    作为奖励,这些资产的更新可以在我的解决方案之外的文件夹中被覆盖,并将在我的解决方案中使用,而无需采取任何额外的操作。

    【讨论】:

      【解决方案3】:

      替换:

      <Image x:Name="imgTest" Source="{local:ImageResource img.jpg}" />
      

      与:

      <Image x:Name="imgTest" Source="{local:ImageResource 'Project.Folder.img.jpg'}" />
      

      然后替换:

      var imageSource = ImageSource.FromResource(Source, typeof(...));
      

      与:

      var imageSource = ImageSource.FromResource(Source);
      

      【讨论】:

        【解决方案4】:

        如果您将图像添加到 Android 可绘制文件夹或 iOS 资源文件夹,则不需要任何扩展。你可以这样做:

         <Image x:Name="imgTest" Source="img.jpg" />
        

        【讨论】:

        • 我知道。关键是我想跨项目共享资源。不要复制每个项目上的文件(我觉得这很烦人)
        • 不是帖子的答案。
        猜你喜欢
        • 2019-10-25
        • 2016-06-26
        • 1970-01-01
        • 2017-08-23
        • 2018-06-17
        • 1970-01-01
        • 2019-08-07
        • 1970-01-01
        • 2018-07-27
        相关资源
        最近更新 更多