Is anyone able to give a short, self-contained example on how to access the camera with Xamarin.Forms 1.3.x? Simply calling the native camera application and retrieving the resulting picture would be great. Displaying a live view on the Xamarin.Forms page would be awesome!
I already tried to use Xamarin.Mobile and Xamarin.Forms.Labs, but I couldn't get any solution to work on both platforms (focussing on Android and iOS for now). Most code snippets found on the web (including stackoverflow) are incomplete, e.g. not showing the implementation of an IMediaPicker object or where to anchor the method for taking pictures.
I finally created a minimum solution for iOS and Android.
The shared project
First, let's look into the shared code. For an easy interaction between the shared
Appclass and the platform-specific code we store a staticInstancewithin thepublic static App:Furthermore, we will display an
Image, which will be filled with content later. So we create a member:Within the
Appconstructor we store theInstanceand create the page content, which is a simplebuttonand the aforementionedimage:The button's click handler calls the event
ShouldTakePicture. It is a public member and the platform-specific code parts will assign to it later on.Finally, we offer a public method for displaying the captured image:
The Android project
On Android we modify the
MainActivity. First, we define a path for the captured image file:At the end of
OnCreatewe can use the staticInstanceof the createdAppand assign an anonymous event handler, which will start a newIntentfor capturing an image:Last but not least, our activity has to react on the resulting image. It will simply push its file path to the shared
ShowImagemethod.That's about it! Just don't forget to set the "Camera" and the "WriteExternalStorage" permission within "AndroidManifest.xml"!
The iOS project
For the iOS implementation we create a custom renderer. Therefore, we add a new file "CustomContentPageRenderer" and add the corresponding assembly attribute right after the using statements:
The
CustomContentPageRendererinherits fromPageRenderer:We override the
ViewDidAppearmethod and add the following parts.Create a new image picker controller referring to the camera:
Present the image picker controller, as soon as the
ShouldTakePictureevent is raised:After taking the picture, save it to the
MyDocumentsfolder and call the sharedShowImagemethod:And finally, we need to handle a cancellation of the image taking process: