Introduction
Xamarin is a platform to develop cross-platform and multi-platform apps (for example, Windows phone, Android, iOS). In the Xamarin platform, the code sharing concept is used. In Xamarin Studio, Visual Studio is also available. Camera app is used to open the camera and take snaps, using the app.
Prerequisites
- Visual Studio 2015 Update 3.
The steps, mentioned below are required to be followed in order to create a Camera App in Xamarin Android app, using Visual Studio 2015.
Step 1
Click File--> select New--> select Project. The project needs to be clicked after opening all the types of projects in Visual Studio or click ing (Ctrl+Shift+N).
Step 2
After opening the New Project, select Installed-->Templates-->Visual C#-->Android-->choose the Blank app (Android).
Now, give your Android app; a name (Ex:sample) and give the path of your project. Afterwards, click OK.
Step 3
Now, go to the Solution Explorer. In Solution Explorer, get all the files and sources in your project.
Now, select Resource-->Layout-->double click to open main.axml page. To write XAML code, you need to select a source.
Choose the Designer Window, if you want to design. Hence, you can design your app.
Step 4
After opening main.axml, file will open the main page designer. You can design this page, as per your wish.
Now, delete the Default hello world button. Go to the source panel and you can see the button coding. You need to delete it.
After deleting XAML code, delete C# button action code.
Go to the MainActivity.cs page. You need to delete the button code.
Step 5
Now, go to the toolbox Window. In the toolbox Window, get all the types of the tools and controls.
You need to go to the toolbox Window and scroll down. You will see all the tools and controls.
You need to drag and drop the button.
Step 6
You need to drag and drop the ImageView.
Step 7
Now, go to the properties Window. You need to edit the Button Id value and Text value
(EX: android:id="@+id/myButton" android:text="@string/openCamera" ).
Step 8
Now, you will edit ImageView Id value and src value.
(Ex: android:id="@+id/imageView1" android:src="@android:drawable/ic_menu_gallery").
Step 9
In this step, go to the Main.axml page Source Panel. Note, the ImageView and Button Id value and source value.
Main.axml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/openCamera" />
- <ImageView android:src="@android:drawable/ic_menu_gallery" android:layout_width="fill_parent" android:layout_height="300.0dp" android:id="@+id/imageView1" android:adjustViewBounds="true" />
- </LinearLayout>
Step 10
In this step, open the String.xml page. Go to Solution Explorer-->Resource-->values-->String.xml.
Step 11
Afterwards, open String.xml file. Write XML code, mentioned below.
String.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="openCamera">Open Camera</string>
- <string name="app_name">CameraAppDemo</string>
- </resources>
Step 12
In this step, add one class file.
Go to Solution Explorer-->Resource-->Right click -->Add-->New Item.
Step 13
Now, choose the Class file and give name BitmapHelpers.cs.
Step 14
Afterwards, create the class file. Write the code, mentioned below.
BitmapHelpers.cs
- namespace cameraapp {
- using System.IO;
- using Android.Graphics;
- public static class BitmapHelpers {
- public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height) {
- BitmapFactory.Options options = new BitmapFactory.Options {
- InJustDecodeBounds = true
- };
- BitmapFactory.DecodeFile(fileName, options);
- int outHeight = options.OutHeight;
- int outWidth = options.OutWidth;
- int inSampleSize = 1;
- if (outHeight > height || outWidth > width) {
- inSampleSize = outWidth > outHeight ?
- outHeight / height :
- outWidth / width;
- }
- options.InSampleSize = inSampleSize;
- options.InJustDecodeBounds = false;
- Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);
- return resizedBitmap;
- }
- }
- }
Step 15
Now, go to the MainActivity.cs page. Write the namespaces and variables, mentioned below.
MainActivity.cs
- using Java.IO;
- using Environment = Android.OS.Environment;
- using Uri = Android.Net.Uri;
- public static class App {
- public static File _file;
- public static File _dir;
- public static Bitmap bitmap;
- }
Step 16
MainActivity.cs
Now, go to the MainActivity.cs page. Write the code, mentioned below.
- public class MainActivity: Activity {
- private ImageView _imageView;
- protected override void OnCreate(Bundle bundle) {
- base.OnCreate(bundle);
-
- SetContentView(Resource.Layout.Main);
- if (IsThereAnAppToTakePictures()) {
- CreateDirectoryForPictures();
- Button button = FindViewById < Button > (Resource.Id.myButton);
- _imageView = FindViewById < ImageView > (Resource.Id.imageView1);
- button.Click += TakeAPicture;
- }
- }
- protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) {
- base.OnActivityResult(requestCode, resultCode, data);
- Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
- Uri contentUri = Uri.FromFile(App._file);
- mediaScanIntent.SetData(contentUri);
- SendBroadcast(mediaScanIntent);
- int height = Resources.DisplayMetrics.HeightPixels;
- int width = _imageView.Height;
- App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
- if (App.bitmap != null) {
- _imageView.SetImageBitmap(App.bitmap);
- App.bitmap = null;
- }
- GC.Collect();
- }
- private void CreateDirectoryForPictures() {
- App._dir = new File(
- Environment.GetExternalStoragePublicDirectory(
- Environment.DirectoryPictures), "CameraAppDemo");
- if (!App._dir.Exists()) {
- App._dir.Mkdirs();
- }
- }
- private bool IsThereAnAppToTakePictures() {
- Intent intent = new Intent(MediaStore.ActionImageCapture);
- IList < ResolveInfo > availableActivities =
- PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
- return availableActivities != null && availableActivities.Count > 0;
- }
- private void TakeAPicture(object sender, EventArgs eventArgs) {
- Intent intent = new Intent(MediaStore.ActionImageCapture);
- App._file = new File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));
- intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file));
- StartActivityForResult(intent, 0);
- }
- }
Step 17
In this step, give the required permissions in your app.
Go to Solution Explorer--> properties-->Right click-->Open.
Step 18
Afterwards, open the properties options. Select Android Manifest-->Required Permissions-->Check CAMERA.
Step 19
Select Android Manifest-->Required Permissions-->Check WRITE_EXTERNAL_STORAGE.
Step 20
If you have Android Virtual device, run the app on it, else connect your Android phone and run the app on it.
Simply, connect your phone and go to Visual Studio. The connected phone will show up in Run menu.
(Ex:LENOVO A6020a40(Android 5.1-API 22)). Click Run option.
Output
After few seconds, the app will start running on your phone.
You can click open camera button.
Now, choose camera and click just once.
You will see the camera app is working successfully.
Summary
Hence, this was the process of creating a Camera App in Xamarin Android app, using Visual Studio 2015.