twitter.com画像をXamarin.Forms for Windows で取ってくる方法を探さないと…
— 田淵 義人@エクセルソフト (@ytabuchi) 2015年5月14日
下記にあるように、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 で分岐処理せずに画像ファイルを共有することはできないのでしょうか?・・・ということで試してみました!
スポンサードリンク
やったことは上記の通り、PCL の Assets 配下に置いた画像ファイルを各プラットフォームにリンクとして追加しただけです
Android: Resources/drawable にビルドアクション「AndroidResource」としてリンクとして追加
iOS: Resources にリンクとして追加
Windows Phone 8.1: プロジェクト直下にリンクとして追加
リンクとして追加は、[追加]-[既存の項目] を選んでから、対象のファイルを選択し「追加」のドロップダウンボタンから「リンクとして追加」を選べばできます
ここまでできたら下記のような感じで 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 による分岐処理はありません・・・これでおためし実行
Windows Phone でも無事に画像を共有して表示できましたね!