0

I have a project that uses SurfaceView to draw some stuff on the screen. User should be able to take screenshot by pressing the button on that screen. Problem is that I always get blank screen when screenshot is taken from SurfaceView. I tried a lot of different answers however none of them worked for me. Here's what I tried:

void takeScre() {
        File file = saveBitmap(getBitmap());
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "image/*");
        startActivity(intent);
    }
    
    Bitmap getBitmap() {
        dots_screen_view.setDrawingCacheEnabled(true);
        return dots_screen_view.getDrawingCache();
    }

//----------

 Bitmap getBitmap() {
        Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        dots_screen_view.draw(c);

        return b;
    }

//-----------

Bitmap getBitmap() {
        Bitmap b = Bitmap.createBitmap(dots_screen_view.getWidth() , dots_screen_view.getHeight(), Bitmap.Config.ARGB_8888);
        dots_screen_view.setDrawingCacheEnabled(false);
        dots_screen_view.layout(0, 0, dots_screen_view.getLayoutParams().width, dots_screen_view.getLayoutParams().height);
        dots_screen_view.draw(new Canvas(b));

        return b;
    }

Also I have tried those libraries:

https://android-arsenal.com/details/1/6985

https://android-arsenal.com/details/1/6163

https://android-arsenal.com/details/3/5293

However none of them works for me. Any other ideas?

Community
  • 1
  • 1
David
  • 3,055
  • 4
  • 30
  • 73

3 Answers3

0

Give Selfie a go... I've used it to create social media posts before without any problems. Its open source so if it works, you can see why it works :)

Carc.me
  • 124
  • 1
  • 6
0

Try below code:

/**
    * Check for permissions and create a snapshot
    *
    * @param activity Activity used by Selfie.
    * @return {@code true} if the screenshot was taken, false otherwise.
    */
   public boolean snap(Activity activity) {
      boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
      if (!hasPermission) {
         ActivityCompat.requestPermissions(activity,
               new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
               REQUEST_WRITE_STORAGE);
         return false;
      } else {
         return takeScreenShot(activity);
      }
   }

   /**
    * This method is responsible for taking the screenshot and creating a file
    *
    * @param activity Activity used by Selfie.
    * @return {@code true} if the screenshot was taken, false otherwise.
    */
   private boolean takeScreenShot(Activity activity) {
      Date now = new Date();
      android.text.format.DateFormat.format(fileFormat, now);

      // create bitmap screen capture
      View v1 = activity.getWindow().getDecorView().getRootView();
      v1.setDrawingCacheEnabled(true);
      Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
      v1.setDrawingCacheEnabled(false);

      // image naming and path to include sd card appending name you choose for file
      String path = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

      File imageFile = new File(path);

      try {
         FileOutputStream outputStream = new FileOutputStream(imageFile);
         bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
         outputStream.flush();
         outputStream.close();
      } catch (IOException ex) {
         return false;
      }

      return true;
   }

Please add write permission inside the manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
0

I was on similar crossroads earlier and had to do a lot of trial runs to take a screenshot of my custom view class.

Try the following code

public String getBitmapFromView() {

    int dwidth,dheight;
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    if(displayMetrics.widthPixels > displayMetrics.heightPixels)
    {
        //orientation is landscape
        dwidth=displayMetrics.heightPixels;
        dheight=displayMetrics.widthPixels;
    }
    else
    {
        dwidth = displayMetrics.widthPixels;
        dheight=displayMetrics.heightPixels;
    }

    setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    //If the view wasnt displayed before this , you will get 0,0 measured widths and heights
    //Thus measure the layout
    measure(MeasureSpec.makeMeasureSpec(dwidth, MeasureSpec.AT_MOST),MeasureSpec.makeMeasureSpec(dheight, MeasureSpec.AT_MOST));

    layout(0, 0, getMeasuredWidth(), getMeasuredHeight());

    //Create a bitmap backed Canvas to draw the into
    Bitmap bitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        if (getMeasuredWidth() == 0 && getMeasuredHeight() == 0) {
          //You will get blank bitmap
            return "";
        } else {
            Canvas c = new Canvas(bitmap);

            //Now that the view is here and we have a canvas, ask the to draw itself into the canvas
            draw(c);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 60, stream);
            byte[] byteArray = stream.toByteArray();
            return Base64.encodeToString(byteArray, Base64.DEFAULT);
        }

}

In my scenario I needed to convert the bitmap into String, however, you can convert it into bytes, use bitmap directly, use OutputStream to write this directly to your file.

Bhavita Lalwani
  • 903
  • 1
  • 9
  • 19