在Android中以编程方式拍摄Surfaceview的屏幕截图

时间:2018-07-23 07:37:43

标签: android screenshot surfaceview

我有一个使用SurfaceView在屏幕上绘制内容的项目。用户应该能够通过按该屏幕上的按钮来截取屏幕截图。问题是,从SurfaceView截取屏幕截图时,我总是空白屏幕。我尝试了很多不同的答案,但是没有一个对我有用。这是我尝试过的:

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;
    }

我也尝试过这些库:

  

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

     

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

     

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

但是他们都不适合我。还有其他想法吗?

3 个答案:

答案 0 :(得分:0)

Selfie继续努力...我曾经用它来创建社交媒体帖子,之前没有任何问题。它是开源的,因此,如果可以正常运行,您可以了解其工作原理:)

答案 1 :(得分:0)

尝试以下代码:

/**
    * 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;
   }

请在清单中添加写权限:

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

答案 2 :(得分:0)

我之前也处于类似的十字路口,不得不进行大量试运行才能对自定义视图类进行截图。

尝试以下代码

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);
        }

}

在我的场景中,我需要将位图转换为String,但是,您可以将其转换为字节,直接使用位图,使用OutputStream将其直接写入文件。