圖片來源
c sharp 的用法
XAML 的用法
<Image Grid.Row="1" Grid.Column="0" Source="platformImage.jpg" />
<Image Source="https://developer.xamarin.com/demo/IMG_3256.JPG?width=640" />
<Image Grid.Row="0" Grid.Column="1" Source="{extMark:ImageResource XFImage.Assets.platformImage.jpg}"/>
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null) return null;
return ImageSource.FromResource(Source);
}
}
<Image Grid.Row="1" Grid.Column="1" Source="{Binding MyImageSource}" />
private ImageSource myImageSource;
public ImageSource MyImageSource
{
get { return myImageSource; }
set { SetProperty(ref myImageSource, value); }
}
#region 從網路下載後,先儲存到本機檔案系統內,接著再讀出來,進行圖片資料綁定
HttpClient client = new HttpClient();
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("MyLocalImage.jpg", CreationCollisionOption.ReplaceExisting);
using (var fooTargetStream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
using (var fooSourceString = await client.GetStreamAsync("https://developer.xamarin.com/demo/IMG_3256.JPG?width=640"))
{
await fooSourceString.CopyToAsync(fooTargetStream);
}
}
file = await folder.GetFileAsync("MyLocalImage.jpg");
var fooTargetReadStream = await file.OpenAsync(FileAccess.Read);
MyImageSource = ImageSource.FromStream(() => fooTargetReadStream);
#endregion
class StringToLocalImage : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string foo1 = value as string;
ImageSource fooImageSource=null;
if (string.IsNullOrEmpty(foo1) == false)
{
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder;
IFile file;
folder = rootFolder.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists).Result;
file = folder.GetFileAsync(foo1).Result;
var fooStream = file.OpenAsync(FileAccess.Read).Result;
Debug.WriteLine($"Length: {fooStream.Length}");
fooImageSource = ImageSource.FromStream(() => fooStream);
}
else
{
}
return fooImageSource;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<Image Grid.Row="2" Grid.Column="1"
Source="{Binding LocalImage2, Converter={StaticResource StringToLocalImage}}" />
Aspect
System.NullReferenceException: Object reference not set to an instance of an object.
。而到底是哪裡發生了問題,也很難找出問題所在,現階段比較好的方法就是使用刪去法。