Android Code Snippet Create bitmap from a view

Here is the inline java code, in order to create bitmap from a view:
B4X:
#if Java
//create bitmap from the ScrollView
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.graphics.Color;

public static Bitmap getBitmapFromView(View view, int height, int width) {
    Bitmap bitmap = Bitmap.createBitmap(width, height, 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);
    return bitmap;
}
#End If

and you can call it like this:
B4X:
Sub btnShare_Click
    
    indexPost = ULV1.FindIDInVisibleItems(Sender)
    
    Dim nativeMe As JavaObject
    nativeMe.InitializeContext

    Private Bitmap1 As Bitmap
    Bitmap1=nativeMe.RunMethod("getBitmapFromView", Array(ULV1.GetVisiblePanels(ULV1.GetPositionForID(indexPost,True)),ULV1.GetVisiblePanels(ULV1.GetPositionForID(indexPost,True)).Height-50dip,100%x))

    Dim Out As OutputStream
    Out = File.OpenOutput(Starter.directory, "Test.png", False)
    Log(Starter.directory)
    Bitmap1.WriteToStream(Out, 100, "PNG")
    Out.Close
    
End Sub

At this example i use Ultimate list view and i create a bitmap from a list view item.
 

yiankos1

Well-Known Member
Licensed User
Longtime User
You can use B4XView.Snapshot from the XUI library to get a snapshot of a view.
Indeed that was easier but i wasn't aware. Here is same code:
B4X:
Sub btnShare_Click

    indexPost = ULV1.FindIDInVisibleItems(Sender)
    
    Private b4x As B4XView
    b4x=ULV1.GetVisiblePanels(ULV1.GetPositionForID(indexPost,True))

    Dim Out As OutputStream
    Out = File.OpenOutput(Starter.directory, "share.jpeg", False)
    Log(Starter.directory)
    b4x.Snapshot.Crop(0,0,100%x,b4x.Height-50dip).WriteToStream(Out, 100, "JPEG")
    Out.Close

End Sub
 
Top