1
8

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-05-06

Xamarinを使ってスマートフォンカメラを制御します。

空のプロジェクトを作成します。

image.png

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

image.png

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

image.png

空白を選択してOK

image.png

パッケージのパーションを確認します。

image.png

パッケージを追加します。

image.png

Xam.Plugin.Mediaパッケージを追加します。

image.png
V5.0.1は、Visual Studio 2019のテンプレートとは、バージョンが合わないので4.0.1.5を導入します
image.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

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

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

1
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
8