Creating A Camera App In Xamarin Android App Using Visual Studio 2015

 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).

Templates

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.

Templates

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.

Templates

Step 4

After opening main.axml, file will open the main page designer. You can design this page, as per your wish.

Templates

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.

Templates

Step 6

You need to drag and drop the ImageView.

Templates

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" ).

Templates

Step 8

Now, you will edit ImageView Id value and src value.

(Ex: android:id="@+id/imageView1" android:src="@android:drawable/ic_menu_gallery").

Templates

Step 9

In this step, go to the Main.axml page Source Panel. Note, the ImageView and Button Id value and source value.

Templates

Main.axml

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">  
  2.     <Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/openCamera" />  
  3.     <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" />  
  4. </LinearLayout>  
Step 10

In this step, open the String.xml page. Go to Solution Explorer-->Resource-->values-->String.xml.

Templates

Step 11

Afterwards, open String.xml file. Write XML code, mentioned below.

String.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="openCamera">Open Camera</string>  
  4.     <string name="app_name">CameraAppDemo</string>  
  5. </resources>  
Templates

Step 12

In this step, add one class file.

Go to Solution Explorer-->Resource-->Right click -->Add-->New Item.

Templates

Step 13

Now, choose the Class file and give name BitmapHelpers.cs.

Templates

Step 14

Afterwards, create the class file. Write the code, mentioned below.

BitmapHelpers.cs
  1. namespace cameraapp {  
  2.     using System.IO;  
  3.     using Android.Graphics;  
  4.     public static class BitmapHelpers {  
  5.         public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height) {  
  6.             BitmapFactory.Options options = new BitmapFactory.Options {  
  7.                 InJustDecodeBounds = true  
  8.             };  
  9.             BitmapFactory.DecodeFile(fileName, options);  
  10.             int outHeight = options.OutHeight;  
  11.             int outWidth = options.OutWidth;  
  12.             int inSampleSize = 1;  
  13.             if (outHeight > height || outWidth > width) {  
  14.                 inSampleSize = outWidth > outHeight ?  
  15.                     outHeight / height :  
  16.                     outWidth / width;  
  17.             }  
  18.             options.InSampleSize = inSampleSize;  
  19.             options.InJustDecodeBounds = false;  
  20.             Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);  
  21.             return resizedBitmap;  
  22.         }  
  23.     }  
  24. }  
Templates

Step 15

Now, go to the MainActivity.cs page. Write the namespaces and variables, mentioned below.

MainActivity.cs
  1. using Java.IO;  
  2. using Environment = Android.OS.Environment;  
  3. using Uri = Android.Net.Uri;  
  4. public static class App {  
  5.     public static File _file;  
  6.     public static File _dir;  
  7.     public static Bitmap bitmap;  
  8. }  
Templates

Step 16

MainActivity.cs

Now, go to the MainActivity.cs page. Write the code, mentioned below.
  1. public class MainActivity: Activity {  
  2.     private ImageView _imageView;  
  3.     protected override void OnCreate(Bundle bundle) {  
  4.         base.OnCreate(bundle);  
  5.         // Set our view from the "main" layout resource  
  6.         SetContentView(Resource.Layout.Main);  
  7.         if (IsThereAnAppToTakePictures()) {  
  8.             CreateDirectoryForPictures();  
  9.             Button button = FindViewById < Button > (Resource.Id.myButton);  
  10.             _imageView = FindViewById < ImageView > (Resource.Id.imageView1);  
  11.             button.Click += TakeAPicture;  
  12.         }  
  13.     }  
  14.     protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) {  
  15.         base.OnActivityResult(requestCode, resultCode, data);  
  16.         Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);  
  17.         Uri contentUri = Uri.FromFile(App._file);  
  18.         mediaScanIntent.SetData(contentUri);  
  19.         SendBroadcast(mediaScanIntent);  
  20.         int height = Resources.DisplayMetrics.HeightPixels;  
  21.         int width = _imageView.Height;  
  22.         App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);  
  23.         if (App.bitmap != null) {  
  24.             _imageView.SetImageBitmap(App.bitmap);  
  25.             App.bitmap = null;  
  26.         }  
  27.         GC.Collect();  
  28.     }  
  29.     private void CreateDirectoryForPictures() {  
  30.         App._dir = new File(  
  31.             Environment.GetExternalStoragePublicDirectory(  
  32.                 Environment.DirectoryPictures), "CameraAppDemo");  
  33.         if (!App._dir.Exists()) {  
  34.             App._dir.Mkdirs();  
  35.         }  
  36.     }  
  37.     private bool IsThereAnAppToTakePictures() {  
  38.         Intent intent = new Intent(MediaStore.ActionImageCapture);  
  39.         IList < ResolveInfo > availableActivities =  
  40.             PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);  
  41.         return availableActivities != null && availableActivities.Count > 0;  
  42.     }  
  43.     private void TakeAPicture(object sender, EventArgs eventArgs) {  
  44.         Intent intent = new Intent(MediaStore.ActionImageCapture);  
  45.         App._file = new File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid()));  
  46.         intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file));  
  47.         StartActivityForResult(intent, 0);  
  48.     }  
  49. }  
Templates

Step 17

In this step, give the required permissions in your app.

Go to Solution Explorer--> properties-->Right click-->Open.

Templates

Step 18

Afterwards, open the properties options. Select Android Manifest-->Required Permissions-->Check CAMERA.

Templates

Step 19

Select Android Manifest-->Required Permissions-->Check WRITE_EXTERNAL_STORAGE.

Templates

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.

Templates

Output

After few seconds, the app will start running on your phone.

You can click open camera button.

Templates

Now, choose camera and click just once.

Templates

You will see the camera app is working successfully.

Templates

Summary

Hence, this was the process of creating a Camera App in Xamarin Android app, using Visual Studio 2015.


Similar Articles