【问题标题】:Load and show image in Xamarin with UWP使用 UWP 在 Xamarin 中加载和显示图像
【发布时间】:2021-05-27 05:28:39
【问题描述】:

我正在编写一个 Xamarin 图片库应用程序,我的 UWP 应用程序具有广泛的文件权限,可以从随机文件路径加载字节,但我无法显示这些字节

image.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes)); 

此代码位于基础项目中,其中字节是通过 UWP 项目中的依赖服务从图像文件加载的。 .xaml 文件包含以下图像定义:

<Image x:Name="image" Aspect="Fill"/>

执行此代码后(imageBytes 不为空)界面上不显示图像。

但是如果我使用

image.Source = ImageSource.FromResource("test.png");

显示来自资源的图像。所以我假设如果正确加载图像应该是可见的。 我没有用 Android 或 iPhone 测试过代码,因为我主要想在 Windows 上使用它,也许以后在 Android 上使用它。 请任何人告诉我我做错了什么或发布指向有效示例代码的链接!

亲切的问候, 沃尔夫冈

【问题讨论】:

    标签: xamarin uwp


    【解决方案1】:

    我正在编写一个 Xamarin 图片库应用程序,我的 UWP 应用程序具有广泛的文件权限,可以从随机文件路径加载字节,但我无法显示这些字节

    造成这个问题的原因有很多,如果你从如下的installedLocation文件夹加载文件,你需要确保文件Build ActionContent类型。

    在测试过程中,它可以正确加载图像字节并很好地显示图像。请尝试以下 DependencyService。

    界面

    public interface IImageStream
    {
        Task<byte[]> GetBytes();
    }
    

    实施

    [assembly: Dependency(typeof(MyImageStream))]
    
    public class MyImageStream :IImageStream
    {
    
        public async Task<byte []> GetBytes()
        {
            Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFile sampleFile = await installedLocation.GetFileAsync("test.png");
    
            byte[] result;
            using (Stream stream = await sampleFile.OpenStreamForReadAsync())
            {
                using (var memoryStream = new MemoryStream())
                {
    
                    stream.CopyTo(memoryStream);
                    result = memoryStream.ToArray();
                }
            }
            return result;
        }
    
    }
    

    用法

    var imageBytes = await DependencyService.Get<IImageStream>().GetBytes();
    image.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
    

    【讨论】:

    • 非常感谢!使用您的代码它可以工作:) 我使用另一个代码从图像中加载字节,就像在其他纯 UWP 应用程序中一样,它可以毫无问题地工作。但是我的方法返回一个不同的字节数组。我不知道为什么它适用于纯 UWP 应用程序。也许那里的图像视图工作方式不同。亲切的问候,沃尔夫冈
    猜你喜欢
    • 2016-06-17
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 2016-09-14
    • 2018-08-28
    • 1970-01-01
    相关资源
    最近更新 更多