差分

ナビゲーションに移動 検索に移動

Xamarin.AndroidでViewをBitmapとして取得する

2,714 バイト追加, 2018年3月1日 (木) 01:35
ページの作成:「Xamarin.AndroidでViewをBitmapとして取得する <source> // Viewを取得する var view = FindViewById<ImageView>(Resource.Id.imageView1); // Bitmap...」
Xamarin.AndroidでViewをBitmapとして取得する

<source>
// Viewを取得する
var view = FindViewById<ImageView>(Resource.Id.imageView1);

// Bitmap化
view.DrawingCacheEnabled = true;
var cache = view.DrawingCache;
if (cache == null)
{
return;
}
var bitmap = Android.Graphics.Bitmap.CreateBitmap(cache);
view.DrawingCacheEnabled = false;
</source>

== スクリーンショットを取る ==
LinearLayoutやFrameLayoutなどの「ほげほげLayout」もViewの派生クラスなので、[[.axmlファイル]]でルート要素となっているLayoutをBitmap化すればスクリーンショットを取ることもできる。
Android 5.0から使えるMediaProjection APIによるスクリーンショットと異なりアプリ外までは取得できないが、この方法は非常にシンプルでパーミッションも不要という利点がある。

: Main.axml
<source>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootLayout1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</source>

: MainActivity.cs
<source>
using Android.App;
using Android.Widget;
using Android.OS;

[Activity(Label = "screenshot", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);

//
var button = FindViewById<Button>(Resource.Id.button1);
var imageView = FindViewById<ImageView>(Resource.Id.imageView1);
var root = FindViewById<LinearLayout>(Resource.Id.rootLayout1);

button.Click += (sender, e) => {
root.DrawingCacheEnabled = true;
var cache = root.DrawingCache;
if (cache == null)
{
return;
}
var bitmap = Android.Graphics.Bitmap.CreateBitmap(cache);
root.DrawingCacheEnabled = false;

imageView.SetImageBitmap(bitmap);
};
}
}
</source>

[[category: Xamarin.Android]]
匿名利用者

案内メニュー