Home > Net >  How to get bitmap from ViewGroup?
How to get bitmap from ViewGroup?

Time:02-03

I'm using recycler view where each item is simple ImageView. My RecyclerView is places in a ViewGroup - FrameLayout.

My task is to get from my FrameLayout - a bitmap.

That is, I need to get a bitmap that will contain pictures that are visible on the screen. That is, I need to draw my recycler on the bitmap, but not the entire recycler, but only the part that is visible on the screen

For example: enter image description here

Is it possible to implement this? Please help me.

CodePudding user response:

This code works for me and is appropriate for your use case :

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@ id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="16dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

this is the code that gives visible items o recyclerView. It is very important to use rootView method

IntentUtils.prepareToShare(this,binding.recyclerView.rootView.drawToBitmap())

if you want to share your image use and see the result see this :

share image in android with intent

CodePudding user response:

Pass your frameLayout to a function,

Bitmap result = loadBitmapFromView(frameLayout);

Following method will generate a view as a bitmap for you.

public static Bitmap loadBitmapFromView(View v) {
    Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
    Canvas c = new Canvas(b);
    v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
    v.draw(c);
    return b;
}
  • Related