2015-04-01 191 views
3

我有这段代码可以截取当前视图,这是一个片段,它存在于一个活动中,活动只有一个背景。以编程方式拍摄整个屏幕的屏幕截图

private File captureScreen() { 

    Bitmap screenshot = null; 
    try { 

     if (view != null) { 

      screenshot = Bitmap.createBitmap(view.getMeasuredWidth(), 
        view.getMeasuredHeight(), Config.ARGB_8888); 
      Canvas canvas = new Canvas(screenshot); 
      view.draw(canvas); 
      // save pics 
      File cache_dir = Environment.getExternalStorageDirectory(); 
      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
      screenshot.compress(Bitmap.CompressFormat.PNG, 90, bytes); 
      File f = new File(cache_dir + File.separator + "screen.png"); 
      f.createNewFile(); 
      FileOutputStream fo = new FileOutputStream(f); 
      fo.write(bytes.toByteArray()); 
      fo.close(); 
      return f; 
     } 
    } catch (Exception e) { 
     // TODO 
    } 
    return null; 
} 

但位图保存不正是我所期待的。 截图仅包含片段元素,但不包含活动背景。我如何将它包含在屏幕截图中?

+1

我建议你从这个问题得到帮助。 http://stackoverflow.com/questions/2661536/how-to-programatically-take-a-screenshot-on-android – 2015-04-01 08:40:06

回答

0

来源:How to programmatically take a screenshot in Android?

// image naming and path to include sd card appending name you choose for file 
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND; 
// create bitmap screen capture 
Bitmap bitmap; 
View v1 = mCurrentUrlMask.getRootView(); 
v1.setDrawingCacheEnabled(true); 
bitmap = Bitmap.createBitmap(v1.getDrawingCache()); 
v1.setDrawingCacheEnabled(false); 

OutputStream fout = null; 
imageFile = new File(mPath); 

try { 
    fout = new FileOutputStream(imageFile); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout); 
    fout.flush(); 
    fout.close(); 

} catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

尝试。它为我工作。而对你来说太

0

调用此方法,传递你想要的屏幕截图外最ViewGroup中:

public Bitmap screenShot(View view) { 
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), 
      view.getHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    view.draw(canvas); 
    return bitmap; 
} 

我已经使用了一段时间在几个不同的应用程序,并没有有任何问题。希望它会帮助