Hi guys. This article gives beginners a very good understanding about how to use Camera & Gallery in Xamain Forms.
Step1: Create the Mobile App (Xamarin Forms) Project
Open VisualStudio 2017 File
New
Project
Choose Cross-Platform Template
Choose MobileApp (Xamarin.Forms )
Name it as CamandDocApp
Click on OK
Choose .NetStandard
Click OK
Step2: Creating a model Gallery.cs
Go to Project CamandDocApp Right Click
Add Class Gallery.cs
File: Gallery.cs
Model as shown in the following code,
Let consider two properties as Path and Index, as we considering Path as OnpropertyChange .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
namespace CamandDocApp { public class Gallery: OnpropertyBase { string _Path; public string Path { get => _Path; set { _Path = value; onPropertyChanged(); ; } } public int index { get; set; } } } |
Step 2: Setting up OnpropertyBase
File: OnpropertyBase.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
namespace CamandDocApp { public class OnpropertyBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; #region Private Methods public void onPropertyChanged([CallerMemberName]string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); #endregion } } |
As the Application is creating through MVVM Pattern , we have declared the Model and
Now we have to create the View of Application
Step 3: Setting up Mainpage.Xaml
File: MainPage.Xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:CamandDocApp" x:Class="CamandDocApp.MainPage"> <StackLayout Padding="5" VerticalOptions="CenterAndExpand"> <Label Text="Pic a Image through Camera or Gallery Location" FontSize="18" HorizontalOptions="CenterAndExpand"/> <Grid x:Name="Picgrid" > <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <AbsoluteLayout Grid.Row="0" Grid.Column="0" HeightRequest="300" BindingContext="{Binding Item1}" x:Name="Item1" > <!--here we are binding the path (Property of Model through MVVM)--> <Image Source="{Binding Path }" BindingContext="{Binding Source={x:Reference Item1}, Path=BindingContext}" AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" Aspect="Fill" /> <!--Here we are consider as Image source "doc.png" through resoursable file we can take any image--> <Image Source="cam.png" WidthRequest="30" HeightRequest="30" AbsoluteLayout.LayoutBounds="0,1,0.5,0.2" AbsoluteLayout.LayoutFlags="All"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding PickPhoto_Click}" CommandParameter="{Binding Source={x:Reference Item1}, Path=BindingContext}" BindingContext="{Binding Source={x:Reference Picgrid}, Path=BindingContext}" /> </Image.GestureRecognizers> </Image> <!--Here we are consider as Image source "cam.png" through resoursable file we can take any image--> <Image Source="doc.png" WidthRequest="30" HeightRequest="30" AbsoluteLayout.LayoutBounds="0.8,1,0.5,0.2" AbsoluteLayout.LayoutFlags="All"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding TakePhoto_Click}" CommandParameter="{Binding Source={x:Reference Item1}, Path=BindingContext}" BindingContext="{Binding Source={x:Reference Picgrid}, Path=BindingContext}" /> </Image.GestureRecognizers> </Image> </AbsoluteLayout> <AbsoluteLayout Grid.Row="0" Grid.Column="1" HeightRequest="300" BindingContext="{Binding Item2}" x:Name="Item2" > <Image Source="{Binding Path }" BindingContext="{Binding Source={x:Reference Item2}, Path=BindingContext}" AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All" Aspect="Fill" /> <!--Here we are consider as Image source "doc.png" through resoursable file we can take any image--> <Image Source="cam.png" WidthRequest="30" HeightRequest="30" AbsoluteLayout.LayoutBounds="0,1,0.5,0.2" AbsoluteLayout.LayoutFlags="All"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding PickPhoto_Click}" CommandParameter="{Binding Source={x:Reference Item2}, Path=BindingContext}" BindingContext="{Binding Source={x:Reference Picgrid}, Path=BindingContext}" /> </Image.GestureRecognizers> </Image> <!--Here we are consider as Image source "cam.png" through resoursable file we can take any image--> <Image Source="doc.png" WidthRequest="30" HeightRequest="30" AbsoluteLayout.LayoutBounds="0.8,1,0.5,0.2" AbsoluteLayout.LayoutFlags="All"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding TakePhoto_Click}" CommandParameter="{Binding Source={x:Reference Item2}, Path=BindingContext}" BindingContext="{Binding Source={x:Reference Picgrid}, Path=BindingContext}" /> </Image.GestureRecognizers> </Image> </AbsoluteLayout> </Grid> </StackLayout> </ContentPage> |
Step 4: Installing NuGet Pakages for Camera/Media and Connectivity
- Xam.Plugin.Media
- Xam.Plugin.Connectivity
Go to Project CamandDocApp Right Click
ManageNuGet Pakages for Solution
Step 5: Initializing CrossMedia
Go to Project .Android MainActivity.cs
Step 6: Creating ViewModel
File: GalleryViewModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
using Plugin.Media; using Plugin.Media.Abstractions; using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; using Xamarin.Forms; namespace CamandDocApp { public class GalleryViewModel:OnpropertyBase { #region PrivateMembers #endregion #region BindingModels //Here we are binding the model of Gallery //Let us consoder model Names as Item1,Item2 private Gallery _Item1; public Gallery Item1 { get { return _Item1; } set { _Item1 = value;onPropertyChanged();} } private Gallery _Item2; public Gallery Item2 { get { return _Item2; } set { _Item2 = value; onPropertyChanged(); } } public ICommand PickPhoto_Click => new Command(PickPhotoClick); public ICommand TakePhoto_Click => new Command(TakePhotoClick); #endregion #region Constructor public GalleryViewModel() { this.Item1 = new Gallery() { index = 0 }; this.Item2 = new Gallery() { index = 1 }; } #endregion #region PublicMethods //As we have declared the View Binding Commamds In MainPage.Xaml,Here we are binding with ICommad function public async void PickPhotoClick(object productGallery) { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsTakePhotoSupported || !CrossMedia.Current.IsCameraAvailable) { //await CurrentPage.DisplayAlert("Option not available", "This option is not supported / available for this device", "OK"); return; } MediaFile _media = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { Directory = "temp", SaveToAlbum = true, CompressionQuality = 75, CustomPhotoSize = 50, PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 2000, DefaultCamera = CameraDevice.Front }); if (_media == null) return; else { var item = productGallery as Gallery; if (item.index == 0) Item1.Path = _media.Path; if (item.index == 1) Item2.Path = _media.Path; } } public async void TakePhotoClick(object picGallery) { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsPickPhotoSupported) { //await CurrentPage.DisplayAlert("Option not available", "This option is not supported / available for this device", "OK"); return; } MediaFile _media = await CrossMedia.Current.PickPhotoAsync(); if (_media == null) return; else { var item = picGallery as Gallery; if (item.index == 0) Item1.Path = _media.Path; if (item.index == 1) Item2.Path = _media.Path; } } #endregion } } |
Step 7: Setting up Required Permissions
Go to Project .Android RightClick Properties
Select Android Manifest
Required Permissions
* CAMERA
* READ_EXTERNAL_STORAGE
* READ_INPUT_STATE (Please check with below Image)
Step 8: Creating paths to save the Images.
Go to Project .Android RightClick Resources
Create New Folder “xml”
Create new file in xml folder “file_paths.xml”
File: file_paths.xml
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8" ?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="my_images" path="Android/data/com.companyname.CamandDocApp/files/Pictures" /> </paths> |
Step 9: Setting up new resource in Android.Manifest.xml
File: Android.Manifest.xml
Add the below code in between the <manifest></manifest>
1 2 3 4 5 |
<application android:label="CamandDocApp.Android"> <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data> </provider> </application> |
For the <application> open tag, setup the label with your application Name
1 |
<application android:label="<your application Name>.Android"> |
Output: