Xamarin Forms:来自外部存储的背景图像

Xamarin Forms: backgroundImage from external storage

我正在开发 Xamarin Forms,它可以成功地将图像写入外部存储,然后应该将其用作 ContentPage 的背景。

我在 ContentPage 的构造函数中这样写:

this.BackgroundImage = "/storage/emulated/0/DCIM/D72D01AEF71348CDBFEED9D0B2F259F7.jpg"

但是背景图片一直不显示。

检查了AndroidManifest,外部存储读写权限设置正确

我错过了什么?

您的代码存在的问题是 BackgroundImage 需要与您的应用捆绑在一起的图像。 Android更新背景图片的实现在这里:

void UpdateBackgroundImage(Page view)
{
    if (!string.IsNullOrEmpty(view.BackgroundImage))
        this.SetBackground(Context.Resources.GetDrawable(view.BackgroundImage));
}

GetDrawable 方法需要来自应用程序资源的图像,这在您的情况下显然不存在。

您应该做的是使用名为 ExternalBackgroundImage 的新 BindableProperty 创建自定义渲染器。然后,您可以在 Android 特定自定义渲染器中将外部图像加载为背景。

PCL 项目

记得将您的当前页面从 ContentPage 更改为 ExternalBackgroundImagePage 以便您可以访问 ExternalBackgroundImage 属性.

public class ExternalBackgroundImagePage : ContentPage 
{
    public static readonly BindableProperty ExternalBackgroundImageProperty = BindableProperty.Create("ExternalBackgroundImage", typeof(string), typeof(Page), default(string));

    public string ExternalBackgroundImage
    {
        get { return (string)GetValue(ExternalBackgroundImageProperty); }
        set { SetValue(ExternalBackgroundImageProperty, value); }
    }
}

Android 项目

[assembly:ExportRenderer (typeof(ExternalBackgroundImagePage), typeof(ExternalBackgroundImagePageRenderer))]
namespace YourProject.Droid
{
    public class ExternalBackgroundImagePageRenderer : PageRenderer 
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            Page view = e.NewElement;
            base.OnElementChanged(e);

            UpdateExternalBackgroundImage(view);
        }

        void UpdateExternalBackgroundImage(Page view)
        {
            if (string.IsNullOrEmpty(view.ExternalBackgroundImage)) 
              return;   

            // Retrieve a bitmap from a file
            var background = BitmapFactory.DecodeFile(view.ExternalBackgroundImage);  

            // Convert to BitmapDrawable for the SetBackground method
            var bitmapDrawable = new BitmapDrawable(background);

            // Set the background image
            this.SetBackground(bitmapDrawable);
        }
    }
}

用法

this.ExternalBackgroundImage = "/storage/emulated/0/DCIM/D72D01AEF71348CDBFEED9D0B2F259F7.jpg"