2014年9月27日 星期六

[android] 抓螢幕截圖 java code

private void getPic() {
        Bitmap mScreenBitmap;
        Matrix mDisplayMatrix;
        mDisplayMatrix = new Matrix();  

        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        if (wm == null) {
            Log.d(TAG,"getPic() wm = null");
            return;
        }
        wm.getDefaultDisplay().getRealMetrics(metrics);              
        float[] dims = {metrics.widthPixels, metrics.heightPixels};

        float degrees = getDegreesForRotation(wm.getDefaultDisplay().getRotation());  
        boolean requiresRotation = (degrees > 0);  
        if (requiresRotation) {  
            // Get the dimensions of the device in its native orientation  
            mDisplayMatrix.reset();  
            mDisplayMatrix.preRotate(-degrees);  
            mDisplayMatrix.mapPoints(dims);  
            dims[0] = Math.abs(dims[0]);  
            dims[1] = Math.abs(dims[1]);  
        }  
 
        mScreenBitmap = SurfaceControl.screenshot((int) dims[0], (int) dims[1]); 

        if (mScreenBitmap == null) {
            Log.d(TAG,"getPic() mScreenBitmap = null");
            return;
        }        

        if (requiresRotation) {  
            // Rotate the screenshot to the current orientation  
            Bitmap ss = Bitmap.createBitmap(metrics.widthPixels, metrics.heightPixels, Bitmap.Config.ARGB_8888);  
            Canvas c = new Canvas(ss);  
            c.translate(ss.getWidth() / 2, ss.getHeight() / 2);  
            c.rotate(degrees);  
            c.translate(-dims[0] / 2, -dims[1] / 2);  
            c.drawBitmap(mScreenBitmap, 0, 0, null);  
            c.setBitmap(null);  
            // Recycle the previous bitmap  
            mScreenBitmap.recycle();  
            mScreenBitmap = ss;  
        }  
  
        // Optimizations  
        mScreenBitmap.setHasAlpha(false);  
        mScreenBitmap.prepareToDraw();        
    }

沒有留言:

張貼留言