代码之家  ›  专栏  ›  技术社区  ›  danbord

Xamarin窗体使用XAML显示嵌入资源中的图像

  •  0
  • danbord  · 技术社区  · 6 年前

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

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

    无法从加载类型“xamarin.forms.xaml.IReferenceProvider” 程序集'xamarin.forms.core,版本=2.0.0.0

    这是我的代码:

    主页.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>
    

    嵌入图像.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;
            }
        }
    }
    
    3 回复  |  直到 6 年前
        1
  •  0
  •   Bruno Caceiro    6 年前

    如果您将图像添加到Android Drawable文件夹或iOS资源文件夹,则不需要任何扩展。您只需执行以下操作:

     <Image x:Name="imgTest" Source="img.jpg" />
    
        2
  •  0
  •   Hutjepower    6 年前

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

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

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

        3
  •  0
  •   Nitika Chopra    6 年前

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

    XYZ.xaml.cs公司

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

    XYZ.xaml(XYZ.xaml)

    <Image x:Name="imgName" />
    

    希望这段代码对您有所帮助!!