是的,很遗憾,您不能将子文件夹用于 android 图像,但您可以将其用于其他 2 个平台,并考虑到这里的差异,这就是我通常所做的。
使用以下 AssetPathHelper(根据您的需要进行修改,在下面我只对 UWP 图像使用子文件夹,而对于乐天动画我在 UWP 和 iOS 中都使用子文件夹)。我还假设.png,如果您使用其他图像类型,则需要处理它。
public static class AssetPathHelper
{
public static readonly string UWPimgRoot = @"Assets\Images\";
public static readonly string UWPanimRoot = @"Assets\Animations\";
public static readonly string iOSanimRoot = @"Animations/"; //note the different slash here, not sure if it's required but that is what works
public static string GetImageSource(string resourceName)
{
var imgFileName = resourceName + ".png"; //! obviously this requires all images used to be pngs
if (Device.RuntimePlatform != Device.UWP)
return imgFileName;
return UWPimgRoot + imgFileName;
}
public static string GetLottieAnimSource(string resourceName)
{
var animFileName = resourceName + ".json";
switch (Device.RuntimePlatform)
{
case Device.iOS:
return iOSanimRoot + animFileName;
case Device.UWP:
return UWPanimRoot + animFileName;
}
return animFileName;
}
}
在以下转换器中使用:
/// <summary>
/// Provides the path to the image taking into account the platform specific location.
/// Can be used without a real binding (i.e. when only a parameter is provided)
/// </summary>
public class ImagePathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter != null)
return AssetPathHelper.GetImageSource(parameter.ToString());
return AssetPathHelper.GetImageSource(value.ToString());
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
所以现在我可以在我的 XAML 中执行此操作,如果图像会发生变化,则作为真正的绑定,否则,只需将图像名称作为转换器参数传递:
<Image
Source="{Binding ConverterParameter=logo_splash, Converter={StaticResource ImagePathConverter}}"/>