【问题标题】:Xamarin Forms: backgroundImage from external storageXamarin Forms:来自外部存储的背景图像
【发布时间】:2018-01-28 04:57:55
【问题描述】:

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

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

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

但背景图像从不显示。

我检查了Android Manifest,读写外部存储的权限设置正确。

我错过了什么?

【问题讨论】:

    标签: image xamarin xamarin.android xamarin.forms storage


    【解决方案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"
    

    【讨论】:

      猜你喜欢
      • 2021-09-05
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 2017-02-28
      • 2017-08-23
      • 1970-01-01
      相关资源
      最近更新 更多