008 [Xamarin] Android 中 快照(Snapshot) View

Post date: 2015/12/8 下午 12:37:37

http://no2don.blogspot.com/2015/08/xamarin-android-snapshot-view.html#more

專案需求,順便筆記一下,將View進行快照,並且在ImageView 物件中顯示

範例說明: 上面是一個LinearLayout按下按鈕後,會將上方的LinearLayout 快照成Bitmap放在下方圖案

Image 009

Layout Code:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<LinearLayout

android:orientation="vertical"

android:minWidth="25px"

android:minHeight="25px"

android:layout_width="match_parent"

android:layout_height="250dp"

android:id="@+id/sampleContainer"

android:background="@drawable/ld">

<Button

android:text="測試"

android:layout_width="100dp"

android:layout_height="wrap_content"

android:id="@+id/button1" />

<Button

android:text="測試2"

android:layout_width="150dp"

android:layout_height="wrap_content"

android:id="@+id/button2"

android:background="#FF0000" />

</LinearLayout>

<Button

android:id="@+id/btnSnap"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="快照上方View" />

<ImageView

android:src="@android:drawable/ic_menu_gallery"

android:layout_width="match_parent"

android:layout_height="250dp"

android:id="@+id/imgResult" />

</LinearLayout>

Snapshot C# Code:

btnSnap.Click += delegate

{

var sample = FindViewById<LinearLayout>(Resource.Id.sampleContainer);

var img = SnapView(sample, sample.Width, sample.Height);

FindViewById<ImageView>(Resource.Id.imgResult).SetImageBitmap(img);

};

public static Bitmap SnapView(View v, int width, int height)

{

Bitmap bitmap;

v.DrawingCacheEnabled=(true);

bitmap = Bitmap.CreateBitmap(v.GetDrawingCache(true));

v.DrawingCacheEnabled=(false);

return bitmap;

}

Result:

Screenshot_2015-08-13-13-37-57