2017-08-19 16 views
1

私はXamarin Formを開発中です。画像を外部記憶装置に正常に書き込んだ後、それをContentPageの背景として使用する必要があります。Xamarinフォーム:外部ストレージからのbackgroundImage

はContentPageのコンストラクタでは、私はこれを書いた:

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

をしかし、背景画像が表示されません。

Androidマニフェストを確認しました。外部記憶装置の読み書きの許可が正しく設定されています。

私には何が欠けていますか?

答えて

1

コードに問題があると、BackgroundImageはあなたのアプリにバンドルされている画像が必要です。背景画像を更新するためのAndroidの実装はここにある:

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

GetDrawable方法は明らかにあなたのケースに存在していないアプリケーションのリソースから画像を期待しています。

あなたがすべきことは、ExternalBackgroundImageという新しいBindablePropertyを持つカスタムレンダラーを作成することです。次に、Android固有のカスタムレンダラーの背景として、外部画像の読み込みを処理できます。

PCLプロジェクト

あなたはExternalBackgroundImageプロパティへのアクセス権を持っているので、ContentPageからExternalBackgroundImagePageにあなたの現在のページを変更することを忘れないでください。

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" 
関連する問題