Image 如何使用Xamarin.Forms中的XAML从嵌入式资源设置图像
在代码中设置图像源并指向PCL项目中特定文件夹中的嵌入图像时(本例中为“图像”),我会这样做:Image 如何使用Xamarin.Forms中的XAML从嵌入式资源设置图像,image,xaml,xamarin,xamarin.forms,embedded-resource,Image,Xaml,Xamarin,Xamarin.forms,Embedded Resource,在代码中设置图像源并指向PCL项目中特定文件夹中的嵌入图像时(本例中为“图像”),我会这样做: backgroundImg.Source = ImageSource.FromResource("Myapp.Images." + imageName + ".jpg"); 在XAML中有这样做的方法吗?使用以下代码: <Image Source="{local:ImageResource YourMobileAppName.YouImageName.jpg}" /> 有关更多信息
backgroundImg.Source = ImageSource.FromResource("Myapp.Images." + imageName + ".jpg");
在XAML中有这样做的方法吗?使用以下代码:
<Image Source="{local:ImageResource YourMobileAppName.YouImageName.jpg}" />
有关更多信息,请阅读您可以从xaml设置图像,如
确保您的图像在iOS资源和Android资源->drawable@Code Pope的回答中是正确的,但您还需要添加一个“ImageResourceExtension”,如@Gerald Versluis的评论中所述 为此,只需创建一个新文件(类)“ImageResourceExtension.cs”,如下所示:
using System;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ImageResourceExtension
{
[ContentProperty (nameof(Source))]
class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
{
return null;
}
var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
return imageSource;
}
}
}
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ImageResourceExtension"
...
<Image Source="{local:ImageResource MyProject.Resources.Images.Logo.png}" />
然后将xmlns:local=“clr namespace:ImageResourceExtension”
添加到xaml文件中,如下所示:
using System;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ImageResourceExtension
{
[ContentProperty (nameof(Source))]
class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
{
return null;
}
var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
return imageSource;
}
}
}
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ImageResourceExtension"
...
<Image Source="{local:ImageResource MyProject.Resources.Images.Logo.png}" />
他特别询问是否从共享项目中检索图像,我以前尝试过此操作,但我得到错误“在xmlns clr命名空间中找不到类型ImageResource”,因此无法生成。是否已将应用程序名称作为前缀插入图像?是否已尝试{local:ImageResource MyApp.Images.testImg.jpg}以及{local:ImageResource MyApp.testImg.jpg}@DarkW1nter您必须实现可在页面上找到的扩展,并将其导入页面根目录中的local
命名空间。不过,您仍然需要进行调整,使其接受动态图像文件名