问题描述
对于 Uno 平台,我需要从“内容”资源加载图像。我正在使用 GetManifestResourceStream
,但它在运行 UWP 项目时返回 null(我没有尝试其他风格)。
为了进一步挖掘,我添加了 GetManifestResourceNames
,但它也返回了一个空数组。
这是我的代码,它位于 UserControl
中(Source
是一个属性):
private void LoadBmpSrc()
{
if (Source == null)
return;
Assembly assembly = GetType().GetTypeInfo().Assembly;
string[] names = assembly.GetManifestResourceNames();
using (Stream stream = assembly.GetManifestResourceStream(Source))
{
bmpSrc = SKBitmap.Decode(stream);
}
}
<controls:ExpandableImage
Grid.Column="0"
Source="ms-appx:///Assets/icons/folder_tab.png"
/>
如果我交换此代码:
<Image
Grid.Column="0"
Source="ms-appx:///Assets/icons/folder_tab.png"
/>
图像显示。
编辑
这是控件的 XAML:
<UserControl
x:Class="UnoTest.Shared.Controls.ExpandableImage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UnoTest.Shared.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:skia="using:SkiaSharp.Views.UWP"
>
<skia:SKXamlCanvas x:Name="EICanvas" PaintSurface="OnPaintSurface" />
</UserControl>
解决方法
您的问题基本上是 Content
图像不被视为 Resources
。
如果要将图像作为资源包含在内,则需要将该文件的构建操作更改为嵌入式资源。更改此设置后,它将显示在
string[] names = assembly.GetManifestResourceNames();
方法调用。
您会注意到图像的名称类似于 ApplicationName.Directory.ImageName.png
。您需要指定此名称才能使用
assembly.GetManifestResourceStream(imageName)
如果您想将内容 Image
数据加载到流中,您可以使用以下代码执行此操作(尚未对其进行测试):
var imageUrl = "ms-appx:///Assets/SplashScreen.png";
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(imageUrl));
using(var stream = await file.OpenStreamForReadAsync())
{
//Use your data here
}
希望这会有所帮助。-