Android screenshot from code. Got it but not perfect

前端 未结 6 549
攒了一身酷
攒了一身酷 2021-02-04 21:47

I\'m trying to take a screenshot in code in Android. Actually the screenshot is the bitmap of the main RelativeLayout. The screenshot is taken but the content appears wrong, the

相关标签:
6条回答
  • 2021-02-04 22:04

    This works good for me:

    View content = findViewById(R.id.myElementForScreenshoot);
    View screenshot = content; // or content.getRootView() for fullscreen
    screenshot.refreshDrawableState();
    screenshot.setDrawingCacheEnabled(true);
    Bitmap b = screenshot.getDrawingCache();    
    

    After this you can process or save bitmap. Hope it helped. Cheers

    0 讨论(0)
  • 2021-02-04 22:16

    I'm assuming you're doing this during creation. Don't!

    use a postDelayed(Runnable, int) to execute the Bitmap bm = Bitmap.createBitmap(v.getDrawingCache()); after the view is drawn.

    also, remove the v.measure() and v.layout() those are methods for the ViewGroup to be calling.

    0 讨论(0)
  • 2021-02-04 22:20

    Remove the lines:

    v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    //v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    v.layout(0, 0, v.getWidth(), v.getHeight());
    
    0 讨论(0)
  • 2021-02-04 22:26

    I think you need to replace the

    RelativeLayout v = (RelativeLayout)findViewById(R.id.main_layout);
    
    v.setDrawingCacheEnabled(true);
    
    v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    
    v.layout(0, 0, v.getWidth(), v.getHeight());
    
    v.buildDrawingCache(true);
    
    Bitmap bm = Bitmap.createBitmap(v.getDrawingCache());
    
    v.setDrawingCacheEnabled(false);
    

    with

    Bitmap bitmap;
    
    View root = findViewById(android.R.id.content);
    
    View v1 = root.getRootView();
    
    v1.setDrawingCacheEnabled(true);
    
    root.setDrawingCacheEnabled(true);
    
    Bitmap bm = Bitmap.createBitmap(root.getDrawingCache());
    
    root.setDrawingCacheEnabled(false);
    
    0 讨论(0)
  • 2021-02-04 22:28

    Specify the screen size in makeMeasureSpec

    ...
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    v.measure(MeasureSpec.makeMeasureSpec(0, size.x),
                MeasureSpec.makeMeasureSpec(0, size.y));
    ...
    

    Also try setting the setDrawingCacheQuality to high, so that it returns a higher resolution bitmap.

    0 讨论(0)
  • 2021-02-04 22:30

    LinearLayout ll = (LinearLayout )findViewById(R.id.layout); ll .setDrawingCacheEnabled(true); Bitmap bm = v1.getDrawingCache();

    Try this

    0 讨论(0)
提交回复
热议问题