眺めて覚える C# Xamarin Forms(12) カメラ制御

#Xamarinを使ってスマートフォンカメラを制御します。
##空のプロジェクトを作成します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/3b95bcd3-0913-1b33-aa92-b5c53426f22c.png)

##モバイルアプリを選択します。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/b5a27fb1-beee-2eeb-0dd6-125be138bcf6.png)

##プロジェクト名を指定して作成

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/e6487bb4-6e84-5033-e966-57f9157345d8.png)

##空白を選択してOK

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/4f066c1a-f19b-201e-10f3-c4028cbc6f49.png)

#パッケージのパーションを確認します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/d71095d1-d996-b25f-e369-8a8b176b8bd2.png)


#パッケージを追加します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/044af80f-34d5-dbc0-fdb0-30c8eaa4c9e1.png)

#Xam.Plugin.Mediaパッケージを追加します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/e54562b9-267c-dcd8-f6cb-e11cbfbf0efd.png)
**V5.0.1は、Visual Studio 2019のテンプレートとは、バージョンが合わないので4.0.1.5を導入します**
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/000efe6d-309e-56f6-d845-0b974e45a093.png)

###readme.txtが表示されます。

```readme.txt
## Android 
In  your BaseActivity or MainActivity (for Xamarin.Forms) add this code:


Add to Activity:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
    Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

The `WRITE_EXTERNAL_STORAGE`, `READ_EXTERNAL_STORAGE` permissions are required, but the library will automatically add this for you. Additionally, if your users are running Marshmallow the Plugin will automatically prompt them for runtime permissions.

Additionally, the following has been added for you:
[assembly: UsesFeature("android.hardware.camera", Required = false)]
[assembly: UsesFeature("android.hardware.camera.autofocus", Required = false)]


You must also add a few additional configuration files to adhere to the new strict mode:

1.) Add the following to your AndroidManifest.xml inside the <application> tags:

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

2.) Add a new folder called xml into your Resources folder and add a new XML file called `file_paths.xml`

Add the following code:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="my_images" path="Pictures" />
    <external-files-path name="my_movies" path="Movies" />
</paths>

You can read more at: https://developer.android.com/training/camera/photobasics.html

## Android Current Activity Setup

This plugin uses the [Current Activity Plugin](https://github.com/jamesmontemagno/CurrentActivityPlugin/blob/master/README.md) to get access to the current Android Activity. Be sure to complete the full setup if a MainApplication.cs file was not automatically added to your application. Please fully read through the [Current Activity Plugin Documentation](https://github.com/jamesmontemagno/CurrentActivityPlugin/blob/master/README.md). At an absolute minimum you must set the following in your Activity's OnCreate method:

'''csharp
CrossCurrentActivity.Current.Init(this, bundle);
'''It is highly recommended that you use a custom Application that are outlined in the Current Activity Plugin Documentation](https://github.com/jamesmontemagno/CurrentActivityPlugin/blob/master/README.md)

```
**上記に従って作業します***

#AndroidManifest.xmlにファイルパスを追加します。
```AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.cam04">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
    <application android:label="Cam04.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>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
```
**この追加は、出力用ファイルパスを指定しています**

次にResourcesフォルダの配下にxmlフォルダを作成してfile_paths.xmlを作成します。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/b72b7bc6-3bc5-c06c-3a57-9e7ba84688ed.png)

```file_paths.xml
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  <external-files-path name="my_images" path="Pictures" />
  <external-files-path name="my_movies" path="Movies" />
</paths>
```
MainPage.xamlを次のようボタンとイメージを追加します。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/08a5940f-bb7d-8d4b-25ed-9b40e4a4c4f7.png)

##MainPage.xml.csは、以下の通りです。

```MainPage.xaml.cs
using Plugin.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Camera
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            var b = new Button() { Text = "Take" };
            var img = new Image() { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand };
            b.Clicked += async (s, e) => {
                await Plugin.Media.CrossMedia.Current.Initialize();
                if (!Plugin.Media.CrossMedia.Current.IsCameraAvailable || !Plugin.Media.CrossMedia.Current.IsTakePhotoSupported) return;
                var mediaOptions = new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Directory = "PictureTest", Name = $"{DateTime.UtcNow}.jpg" // 保存ファイル名
                };
                var file = await CrossMedia.Current.TakePhotoAsync(mediaOptions);
                if (file == null) return;
                img.Source = ImageSource.FromStream(() =>
                {
                    return file.GetStream();
                });
            };
            Content = new StackLayout() { Children = { b, img } };
        }
        
    }
}

```

##実行すると
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/c82a1a0b-6c19-6333-2996-400bb4d90709.png)