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



>我正在开发一种Xamarin Form,它可以成功地将图像写入外部存储,然后应该将其用作内容页面的背景。

在内容页面的构造函数中,我写了这个:

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

但背景图像从未显示。

我检查了Android清单,读取和写入外部存储的权限设置正确。

我错过了什么?

代码的问题在于,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); }
}
}

安卓项目

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

最新更新