如何在Xamarin.Forms中使用XAML从Embedded资源中设置一个图像。

问题描述 投票:2回答:3

当在代码中设置图像源并指向PCL项目中特定文件夹中的嵌入式图像时(在本例中为'图像'),我会这样做。

backgroundImg.Source = ImageSource.FromResource("Myapp.Images." + imageName + ".jpg");

在XAML中有没有办法做到这一点?

image xaml xamarin xamarin.forms embedded-resource
3个回答
2
投票

@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;
        }
    } 
}

然后添加 xmlns:local="clr-namespace:ImageResourceExtension" 到你的xaml文件,就像这样。

<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"
         ...

现在你可以用这样的xaml代码来访问一个嵌入式资源。

<Image Source="{local:ImageResource MyProject.Resources.Images.Logo.png}" />

1
投票

使用以下代码。

<Image Source="{local:ImageResource YourMobileAppName.YouImageName.jpg}" />

更多信息,请阅读 此处


-2
投票

你可以从xaml中设置图像,如 <Image Source="imageName" Aspect="AspectFit" />确保你的图片在iOS资源和Android资源中可用->可绘制。

© www.soinside.com 2019 - 2024. All rights reserved.