[Andorid]How to capture screen

[日本語]

 

I introduce how to capture screen on Android this time.

 

環境:Android Studio 2.2.1, API 19

 

You can capture screen every views on Android.

At first, use setDrawingCacheEnabled(true) and getDrawingCache, and you can get view's capture.

 

And you must use setDrawingCacheEnabled(false) after getting view's capture.

private View view1;

・・・・・・・・・・・・・・・・・

view1.setDrawingCacheEnabled(true);

Bitmap bmp = Bitmap.createBitmap(view1.getDrawingCache());

view1.setDrawingCacheEnabled(false);

 

Sample code is below.

package net.studioks.sample1;

 

import android.app.Activity;

import android.graphics.Bitmap;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.RelativeLayout;

import android.widget.TextView;

 

public class sample1 extends Activity {

  private TextView textView1;

  private ImageView imageView1;

  private Button button1;

 

  RelativeLayout relativeLayout;

 

  @Override

  public void onCreate(Bundle bundle) {

    super.onCreate(bundle);

    relativeLayout = new RelativeLayout(this);

    setContentView(relativeLayout);

 

    textView1.setText("Test");

    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(200,100);

    params1.leftMargin = 10;

    params1.topMargin = 0;

    relativeLayout.addView(textView1,params1);

 

    imageView1.setScaleType(ImageView.ScaleType.FIT_XY);

    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(400,400);

    params2.leftMargin = 10;

    params2.topMargin = 110;

    relativeLayout.addView(imageView1,params2);

 

    button1.setText("Get Image");

    button1.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View v) {

        textView1.setDrawingCacheEnabled(true);

        Bitmap bmp = Bitmap.createBitmap(textView1.getDrawingCache());

        textView1.setDrawingCacheEnabled(false);

        imageView1.setImageBitmap(bmp);

      }

    });

    RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(400,400);

    params3.leftMargin = 10;

    params3.topMargin = 515;

    relativeLayout.addView(button1,params3);

  }

}