Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import android.app.Activity;
import android.graphics.Bitmap;

import android.graphics.Matrix;

import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;

public class Main {
    /**
     * get a screen shot with size : width X height.
     */
    public static Bitmap getScreenShot(Activity activity, int width, int height) {
        if (activity == null || width < 1 || height < 1) {
            return null;
        }
        Window window = activity.getWindow();
        if (window == null) {
            return null;
        }
        View decorView = window.getDecorView();
        if (decorView == null) {
            return null;
        }
        decorView.setDrawingCacheEnabled(true);
        Bitmap screenShot = decorView.getDrawingCache(true);
        if (screenShot == null) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.postScale((float) width / screenShot.getWidth(), (float) height / screenShot.getHeight());
        Bitmap drawingCache = Bitmap.createBitmap(screenShot, 0, 0, screenShot.getWidth(), screenShot.getHeight(),
                matrix, true);
        decorView.destroyDrawingCache();
        screenShot.recycle();
        return drawingCache;
    }

    /**
     * get a screen shot with default screen size.
     */
    public static Bitmap getScreenShot(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        return getScreenShot(activity, width, height);
    }
}