Taking a screenshot of a particular view

Published June 17, 2020

To take a screenshot of particular view in android we need to get drawable of that view and convert drawable into bitmap and save that bitmap in file.

Take Screenshot programmatically

private void takeScreenShot()
{
    Bitmap viewBitmap = Bitmap.createBitmap(lnr_takshot.getWidth(), lnr_takshot.getHeight(), Bitmap.Config.RGB_565);
    Canvas viewCanvas = new Canvas(viewBitmap);
    Drawable backgroundDrawable = lnr_takshot.getBackground();

    if(backgroundDrawable != null){
        // Draw the background onto the canvas.
        backgroundDrawable.draw(viewCanvas);
    }
    else{
        viewCanvas.drawColor(Color.GREEN);
        // Draw the view onto the canvas.
        lnr_takshot.draw(viewCanvas);
    }

    // Write the bitmap generated above into a file.
    String fileStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    OutputStream outputStream = null;
    try{
        imgFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileStamp + ".png");
        outputStream = new FileOutputStream(imgFile);
        viewBitmap.compress(Bitmap.CompressFormat.PNG, 40, outputStream);
        outputStream.close();
        txt_content.setText("Path : "+imgFile.getAbsolutePath());
    }
    catch(Exception e){
        e.printStackTrace();
        txt_content.setText("Error while taking screenshot: "+e.getMessage());
    }

}

In this post we are going to learn how to take screen shot of particular view in android.

Let's get started.

Step 1: Create Android application in Android studio.

Step 2: Update xml file with below code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#49D6E6"
    tools:context=".MainActivity">

   <LinearLayout
       android:id="@+id/lnr_takshot"
       android:layout_width="match_parent"
       android:layout_weight="1"
       android:background="#FFF"
       android:layout_margin="5dp"
       android:layout_height="match_parent">
       <ImageView
           android:layout_width="match_parent"
           android:src="@drawable/chuki"
           android:layout_height="match_parent" />

   </LinearLayout>
    <TextView
        android:id="@+id/txt_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:text=""
        android:textColor="#FFF"
        android:textSize="20sp"
        android:layout_margin="5dp"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btn_takeshot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center"
        android:text="Take ScreenShot"
        android:textColor="#FFF"
        android:minEms="8"
        android:layout_margin="20dp"
        android:background="#C731E0"
        />

</LinearLayout>

 

Step 3: Update Activity file with below code

package com.rrtutors.capturescreenshot;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    TextView txt_content;
    Button btn_takeshot;
    LinearLayout lnr_takshot;
    File imgFile;
    int EXTERNAL_STORAGE_PERMISSION=200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt_content=findViewById(R.id.txt_content);
        btn_takeshot=findViewById(R.id.btn_takeshot);
        lnr_takshot=findViewById(R.id.lnr_takshot);
        btn_takeshot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txt_content.setText("");
                checkPermisstions();
               }
        });
    }

    private void takeScreenShot()
    {
        Bitmap viewBitmap = Bitmap.createBitmap(lnr_takshot.getWidth(), lnr_takshot.getHeight(), Bitmap.Config.RGB_565);
        Canvas viewCanvas = new Canvas(viewBitmap);
        Drawable backgroundDrawable = lnr_takshot.getBackground();

        if(backgroundDrawable != null){
            // Draw the background onto the canvas.
            backgroundDrawable.draw(viewCanvas);
        }
        else{
            viewCanvas.drawColor(Color.GREEN);
            // Draw the view onto the canvas.
            lnr_takshot.draw(viewCanvas);
        }

        // Write the bitmap generated above into a file.
        String fileStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        OutputStream outputStream = null;
        try{
            imgFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileStamp + ".png");
            outputStream = new FileOutputStream(imgFile);
            viewBitmap.compress(Bitmap.CompressFormat.PNG, 40, outputStream);
            outputStream.close();
            txt_content.setText("Path : "+imgFile.getAbsolutePath());
        }
        catch(Exception e){
            e.printStackTrace();
            txt_content.setText("Error while taking screenshot: "+e.getMessage());
        }

    }

    private void checkPermisstions()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if(ContextCompat.checkSelfPermission(
                    getApplicationContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED)  {
                // You can use the API that requires the permission.
                takeScreenShot();
            }else
            {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION);
            }
        }else
        {
            takeScreenShot();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length>0)
        {
            takeScreenShot();
        }
    }
}

 

If we want to store image in External storage we need to add permissions in manifest and take user permissions by below code

private void checkPermisstions()
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if(ContextCompat.checkSelfPermission(
                getApplicationContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED)  {
            // You can use the API that requires the permission.
            takeScreenShot();
        }else
        {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION);
        }
    }else
    {
        takeScreenShot();
    }

}

 

Step 4: Add permissions in manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 

Step 5: Run application

Take Screenshot programatically

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

942 Views