しっぽを追いかけて

ぐるぐるしながら考えています

Unity と猫の話題が中心   掲載内容は個人の私見であり、所属組織の見解ではありません

Xamarin.Forms for Windows で画像ファイルを共有して表示する

twitter.com

下記にあるように、PCL に埋め込まれたリソースにアクセスできないという Xamarin.Forms for Windows の制限事項があるため、普通に PCL に埋め込まれた画像ファイルを共有しようとしてもうまくいきません

Windows Platform Features - Xamarin | Microsoft Docs

Limitations

There are some limitations that you should be aware of:

~ 中略 ~

Resources - due to the WinRT default trust level, embedded resource loading from a different assembly will not work unless the ReflectionPermission on the source assembly is correctly set. This permission cannot be set on PCL assemblies.

Device.OS で分岐処理せずに画像ファイルを共有することはできないのでしょうか?・・・ということで試してみました!

スポンサードリンク

f:id:matatabi_ux:20150517213439p:plain

やったことは上記の通り、PCL の Assets 配下に置いた画像ファイルを各プラットフォームにリンクとして追加しただけです

  • Android: Resources/drawable にビルドアクション「AndroidResource」としてリンクとして追加

  • iOS: Resources にリンクとして追加

  • Windows Phone 8.1: プロジェクト直下にリンクとして追加

リンクとして追加は、[追加]-[既存の項目] を選んでから、対象のファイルを選択し「追加」のドロップダウンボタンから「リンクとして追加」を選べばできます

f:id:matatabi_ux:20150517214326p:plain

f:id:matatabi_ux:20150517214335p:plain

ここまでできたら下記のような感じで PCL 側にある App.cs にて、ImageSource を取得して Image.Source に設定してみます

public class App : Application
{
    public App()
    {
        // The root page of your application
        MainPage = new ContentPage
        {
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children = {
                  new Image
                  {
                      Source = ImageSource.FromFile("cat.jpg"),
                  },
               }
            }
        };
    }

    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }
}

Device.OS による分岐処理はありません・・・これでおためし実行

f:id:matatabi_ux:20150517214946p:plain f:id:matatabi_ux:20150517214954p:plain f:id:matatabi_ux:20150517215002p:plain

Windows Phone でも無事に画像を共有して表示できましたね!