Android 레이아웃(layout)을 그림(bitmap)으로 변환

이전에 IOS 동료와 스크린샷을 어떻게 캡처하는지 토론한 적이 있는데, 그때도 몰랐는데, 어떻게 리스트를 캡처할 수 있겠는가?어쨌든 리스트는 위아래로 미끄러질 수 있잖아!최근에 원생 레이아웃의 인터페이스에서 신체검사 보고서를 작성하는 것이 필요합니다. 이 인터페이스는 H5로 하면 pdf 인쇄를 생성할 수 있다는 것을 알고 있습니다.그러나 지금은 프린터로bitmap이 돌아가는 byte수 그룹 파일을 출력할 수 있기 때문에 페이지 레이아웃을bitmap 그림으로 변환해야 한다.
레이아웃 파일이 화면 높이를 초과하지 않았을 때:
private Bitmap getViewBitmap(View v) {
        v.clearFocus();
        v.setPressed(false);
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        return bitmap;
    }

레이아웃이 화면 높이를 초과하면 슬라이딩은 Scrollview 처리됩니다.
public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

상기 두 가지 방법은layout을 만족시켜bitmap을 생성하고bitmap은 그림을 다시 생성하여 로컬에 저장할 수 있다.
public static void savePhotoToSDCard(Bitmap photoBitmap, String path, String photoName) {
        if (checkSDCardAvailable()) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File photoFile = new File(path, photoName + ".png");
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(photoFile);
                if (photoBitmap != null) {
                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
                        fileOutputStream.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                photoFile.delete();
                e.printStackTrace();
            } catch (IOException e) {
                photoFile.delete();
                e.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//     SD 
public static boolean checkSDCardAvailable() {
    return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}


Activity에서 사용하는 방법:
//   contentLly        
Bitmap bitmap = getBitmapByView(contentLly);                
ImageUtils.savePhotoToSDCard(bitmap, "/sdcard/file", "img");

지정한 너비나 지정한 비율에 따라bitmap 방법을 다시 설정합니다
    //     bitmap        x,   y bitmap  
    public static Bitmap  transform(Bitmap b, float x, float y) {
        int w = b.getWidth();
        int h = b.getHeight();
        float sx = (float) x / w;
        float sy = (float) y / h;
        Matrix matrix = new Matrix();

        //                     ,         
        // float bigerS = Math.max(sx, sy);
        // matrix.postScale(bigerS, bigerS);

        //           
        matrix.postScale(sx, sy);
        Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w, h, matrix, true);
        return resizeBmp;
    }

화면에 표시되지 않은 컨트롤도bitmap을 가져올 수 있습니다.layout을 먼저 진행해야 합니다.
    //   View      View        ,        ,          。                :
    private void layoutView(View v) {
        DisplayMetrics metric = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     //     (  )
        int height = metric.heightPixels;   //     (  )
        //   View                  
        v.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(10000, View.MeasureSpec.AT_MOST);
        /**   ,measure  ,       View   ,    View.layout       。
         *      layout   ,View                。
         */
        v.measure(measuredWidth, measuredHeight);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /**      canvas     ,      */

        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

사용 방법:
//           
layoutView(contentLly);

//   bitmap  
loadBitmapFromView(contentLly);

좋은 웹페이지 즐겨찾기