Category / Section
How to display images taken from the camera on Xamarin.Forms ListView (SfListView)
1 min read
You can display images taken by camera in SfListView by loading the Image in the SfListView.ItemTemplate. Refer to the steps below to load the image taken from camera,
STEP 1: Install the Xam.Plugin.Media Nuget package to the shared code project. To know more about using the Media plugin for Xamarin refer here.
STEP 2: Take a photo using CrossMedia plugin and convert it to ImageSource.
namespace SfListViewSample { public class ViewModel { private int count = 0; public Command<object> TakePhotoCommand { get; set; } public ViewModel() { ContactsInfo = new ObservableCollection<ListViewContactsInfo>(); TakePhotoCommand = new Command<object>(OnTakePhotoClicked); } private async void OnTakePhotoClicked(object obj) { count += 1; var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "Media\\Pictures", Name = "Image" + count, SaveToAlbum = false, CompressionQuality = 75, CustomPhotoSize = 50, MaxWidthHeight = 2000, }); var details = new ListViewContactsInfo() { ContactNumber = random.Next(100, 400).ToString() + "-" + random.Next(500, 800).ToString() + "-" + random.Next(1000, 2000).ToString(), ContactName = CustomerNames[count], }; if (file == null) return; details.ContactImage = ImageSource.FromStream(() => { var stream = file.GetStream(); return stream; }); ContactsInfo.Add(details); } } }
STEP 3: Bind the Button.Command to take a photo. Display the image in the ItemTemplate using FFImageLoading.
<StackLayout> <Button Text="Take photo" Command="{Binding TakePhotoCommand}" HeightRequest="50"/> <syncfusion:SfListView x:Name="listView" AutoFitMode="Height" SelectionMode="Single" ItemsSource="{Binding ContactsInfo}"> <syncfusion:SfListView.ItemTemplate> <DataTemplate> <Frame BackgroundColor="White" Padding="1" HasShadow="{OnPlatform Android=true, iOS=false, UWP=true, WPF=true}"> <Grid> <ffimage:CachedImage Source="{Binding ContactImage}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" HeightRequest="150" WidthRequest="150" Aspect="AspectFill"/> <StackLayout Grid.Column="1" Padding="10,0,0,0"> ... </StackLayout> </Grid> </Frame> </DataTemplate> </syncfusion:SfListView.ItemTemplate> </syncfusion:SfListView> </StackLayout>