interface onScreenShotFinishedListener
{
  void onScreenShotFinished(@Nullable Bitmap pBitmap);
}

void screenShot(@NonNull Window window,@NonNull View pView, @NonNull onScreenShotFinishedListener pListener)
{
  Rect tRect = calcViewRect(pView);
  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
  {
    Bitmap tBitmap = Bitmap.createBitmap(tRect.width(), tRect.height(), Bitmap.Config.ARGB_8888, true);
    try
    {
      PixelCopy.request(window, tRect, tBitmap, new PixelCopy.OnPixelCopyFinishedListener()
      {
        @Override
        public void onPixelCopyFinished(int copyResult)
        {
          if (PixelCopy.SUCCESS == copyResult)
          {
            pListener.onScreenShotFinished(tBitmap);
          }
          else
          {
            pListener.onScreenShotFinished(null);
          }
        }
      }, new Handler(Looper.getMainLooper()));
    }
    catch (Exception e)
    {
      e.printStackTrace();
      pListener.onScreenShotFinished(null);
    }
  }
  else
  {
    pView.setDrawingCacheEnabled(true);
    try
    {
      Bitmap tBitmap = Bitmap.createBitmap(pView.getDrawingCache());
      pListener.onScreenShotFinished(tBitmap);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      pListener.onScreenShotFinished(null);
    }
    finally
    {
      pView.setDrawingCacheEnabled(false);
    }
  }
}

private Rect calcViewRect(View pTargetView)
{
  int[] location = new int[2];
  pTargetView.getLocationOnScreen(location);
  Rect tRect = new Rect(location[0],
    location[1],
    location[0] + pTargetView.getWidth(),
    location[1] + pTargetView.getHeight());
  return tRect;
}

arrow
arrow
    文章標籤
    Android
    全站熱搜
    創作者介紹
    創作者 你是誰 的頭像
    你是誰

    你是誰的部落格

    你是誰 發表在 痞客邦 留言(0) 人氣()