Skip to content

Instantly share code, notes, and snippets.

@3t14
Created January 28, 2017 01:47
Show Gist options
  • Save 3t14/e9f679a9896772958ac46b09697776d9 to your computer and use it in GitHub Desktop.
Save 3t14/e9f679a9896772958ac46b09697776d9 to your computer and use it in GitHub Desktop.
using System;
using Plugin.Media;
using Xamarin.Forms;
namespace HelloCamera
{
public class App : Application
{
// 後の参照用
Image photoImage;
public App()
{
photoImage = new Image { };
var button = new Button
{
Text = "写真撮影する"
};
// The root page of your application
var content = new ContentPage
{
Title = "HelloCamera",
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "写真撮影サンプル"
},
button,
photoImage
}
}
};
button.Clicked += async (sender, e) =>
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable
|| !CrossMedia.Current.IsTakePhotoSupported)
{
await content.DisplayAlert("警告", "カメラデバイスが使えません", "OK");
}
// 写真撮影する
var file = await CrossMedia.Current.TakePhotoAsync(
// 引数は保存条件を指定
new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Photos", // 保存フォルダ名
Name = "sample.jpg", // 保存ファイル名。
// 既存の場合は"sample_2.jpg"といったようにナンバリングされる
// SaveToAlbum = true, // この場合はデバイスの写真アルバムに記録
// 写真サイズ、Customの場合はCustomPhotoSizeで%指定
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
// デフォルトのカメラ指定(FrontもしくはRearで指定
DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Rear
}
);
// 撮影に失敗の場合は何もしない
if (file == null) return;
// FromStreamメソッドはストリームを返すメソッドを引数にもつ
photoImage.Source = ImageSource.FromStream(() => {
var stream = file.GetStream(); // ファイルストリームを取得
file.Dispose(); // ファイルを解放
return stream; // 取得したストリームを引き渡す
});
};
MainPage = new NavigationPage(content);
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment