我正在开发一个Xamarin Form
,它将图像成功写入外部存储,然后将其用作ContentPage的背景。
在ContentPage的构造函数中,我写了这个:
this.BackgroundImage = "/storage/emulated/0/DCIM/D72D01AEF71348CDBFEED9D0B2F259F7.jpg"
但背景图片永远不会显示。
我检查了Android Manifest,并且正确设置了读写外部存储的权限。
我错过了什么?
答案 0 :(得分:1)
您的代码存在的问题是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"