你的Xamarin Forms PCL不知道Android中的URI是什么,因为它是平台特定的,所以:
ImageSource.FromFile(path);
无法工作。
如果您正在处理特定于平台的功能,即从Android加载图像。我建议采用以下方法:
在Xamarin Forms PCL上创建一个接口,如:
public interface IPhoto
{
Task<Stream> GetPhoto ();
}
然后在Android中,您实现该接口并将其注册到DependencyService
中:
[assembly: Xamarin.Forms.Dependency(typeof(PhotoImplementation))]
namespace xpto
{
public class PhotoImplementation : Java.Lang.Object, IPhoto
{
public async Task<Stream> GetPhoto()
{
var memoryStream = new MemoryStream();
using (var source = System.IO.File.OpenRead(path))
{
await source.CopyToAsync(memoryStream);
}
return memoryStream;
}
}
}
在Xamarin Forms PCL代码中获取图像:
var image = ImageSource.FromStream ( () => await DependencyService.Get<IPhoto>().GetPhoto());
欲了解更多详细信息,请咨询此链接。
注意1:如果您也实现了IPhoto接口,则此功能也适用于iOS。
注意2:有一个很有帮助的库可以实现这种功能,来自Xamarin-Forms-Labs,名为Camera。
更新(共享项目解决方案)
根据评论中的要求,我们可以在共享项目而不是PCL中使用此项功能。
1- 在共享项目中放置IPhotoInterface
。
2- 在Android/iOS项目中实现该接口:
public class PhotoImplementation : IPhoto
{
public async Task<Stream> GetPhoto()
{
}
}
3 - 在共享项目中使用:
IPhoto iPhotoImplementation;
#if __ANDROID__
iPhotoImplementation = new shared_native.Droid.GetPicture();
#elif __IOS__
iPhotoImplementation = new shared_native.iOS.GetPicture();
#endif
var image = ImageSource.FromStream ( () => await iPhotoImplementation.GetPhoto());
注意: shared_native
是我的解决方案的命名空间,Droid/iOS
分别是 Android 和 iOS 项目。
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
读取。 - Episodex