make Snapshot - Android User Interface

Android examples for User Interface:ScreenShot

Description

make Snapshot

Demo Code


//package com.java2s;
import android.app.Activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;

import android.util.Log;

import android.view.View;
import android.view.View.MeasureSpec;
import android.view.Window;

public class Main {
    private static final String TAG = "ViewUtils";

    public static Bitmap makeSnapshot(View view) {
        if (view == null) {
            Log.w(TAG, "Argument 'view' is null at makeSnapshot(View)");
            return null;
        }/*from w w w.j  a v a2  s  .c  o m*/

        int width = view.getWidth();
        int height = view.getHeight();

        if (width <= 0 || height <= 0) {
            Log.w(TAG,
                    "The size of the view is invalid at makeSnapshot(View)");
            return null;
        }

        Bitmap snapshot = null;
        try {
            snapshot = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(snapshot);
            view.draw(canvas);
        } catch (OutOfMemoryError er) {
            Log.w(TAG, "OutOfMemoryError at makeSnapshot(View)", er);
        } catch (Exception e) {
            Log.w(TAG, "Exception at makeSnapshot(View)", e);
        }

        return snapshot;
    }

    public static Bitmap makeSnapshot(View view, int expectedWidht,
            int expectedHeight) {
        if (view == null) {
            Log.w(TAG,
                    "Argument 'view' is null at makeSnapshot(View, int, int)");
            return null;
        }
        if (expectedWidht <= 0 || expectedHeight <= 0) {
            Log.w(TAG,
                    "Arguemnt 'expectedWidht' and 'expectedHeight' must > 0");
            return null;
        }

        int widthSpec = MeasureSpec.makeMeasureSpec(expectedWidht,
                MeasureSpec.EXACTLY);
        int heightSpec = MeasureSpec.makeMeasureSpec(expectedHeight,
                MeasureSpec.EXACTLY);
        view.measure(widthSpec, heightSpec);
        view.layout(0, 0, expectedWidht, expectedHeight);

        return makeSnapshot(view);
    }

    public static Bitmap makeSnapshot(Activity activity) {
        if (activity == null) {
            Log.w(TAG,
                    "Argument 'activity' is null at makeSnapshot(Activity)");
            return null;
        }
        return makeSnapshot(activity.getWindow());
    }

    public static Bitmap makeSnapshot(Window window) {
        if (window == null) {
            Log.w(TAG, "Argument 'window' is null at makeSnapshot(Window)");
            return null;
        }
        return makeSnapshot(window.getDecorView());
    }
}

Related Tutorials