Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capture bitmap from view android [duplicate]

Tags:

android

I have posted same question but it's in near to my problem that's why i have posted it second time

Hi i want to capture image from RelativeLayout, for that i have used below code

   captureRelativeLayout.setDrawingCacheEnabled(true);
   bitmap = captureRelativeLayout.getDrawingCache(true).copy(
                Config.ARGB_8888, false);

the problem is that when i start activity and get image from that view at that time it will work fine, but if i use it second time, the image is not being refreshed, means that previous bitmap is every time i getting.

Now if i close my activity and agian start it then i will get updated image but again not in second time :( for more information look at the can't share image properly android

like image 258
Siddhpura Amit Avatar asked Feb 28 '14 13:02

Siddhpura Amit


2 Answers

Here are two ways to convert a view to a bitmap:

Use Drawing Cache:

RelativeLayout view = (RelativeLayout)findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheEnabled(false);

I've had some issue with the drawing cache method when the view is very large (for example, a TextView in a ScrollView that goes far off the visable screen). In that case, using the next method would be better.

Use Canvas:

RelativeLayout view = (RelativeLayout)findViewById(R.id.relativelayout);
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null) {
    bgDrawable.draw(canvas);
} else {
    canvas.drawColor(Color.WHITE);
}
view.draw(canvas);
like image 174
Suragch Avatar answered Sep 30 '22 12:09

Suragch


There is a Kotlin extension function in Android KTX:

val config: Bitmap.Config = Bitmap.Config.ARGB_8888
val bitmap = canvasView.drawToBitmap(config)
like image 34
Rathi J Avatar answered Sep 30 '22 11:09

Rathi J