Vintage appMaker의 Tech Blog

[kotlin] RecyclerView full size capture - 코틀린 변환 본문

Source code or Tip/Android(Java, Kotlin)

[kotlin] RecyclerView full size capture - 코틀린 변환

VintageappMaker 2020. 8. 16. 17:02

원본링크 
https://stackoverflow.com/questions/30085063/take-a-screenshot-of-recyclerview-in-full-length

 

Take a screenshot of RecyclerView in FULL length

I want to get a "full page" screenshot of the activity. The view contains a RecyclerView with many items. I can take a screenshot of the current view with this function: public Bitmap getScreenBi...

stackoverflow.com

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import androidx.collection.LruCache
import androidx.recyclerview.widget.RecyclerView

fun getScreenshotFromRecyclerView(view: RecyclerView): Bitmap? {
    val adapter = view.adapter
    var bigBitmap: Bitmap? = null
    if (adapter != null) {
        val size = adapter.itemCount
        var height = 0
        val paint = Paint()
        var iHeight = 0
        val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
        // Use 1/8th of the available memory for this memory cache.
        val cacheSize = maxMemory / 8
        val bitmaCache =
            LruCache<String, Bitmap>(cacheSize)
        for (i in 0 until size) {
            val holder =
                adapter.createViewHolder(view, adapter.getItemViewType(i))
            adapter.onBindViewHolder(holder, i)
            holder.itemView.measure(
                View.MeasureSpec.makeMeasureSpec(
                    view.width,
                    View.MeasureSpec.EXACTLY
                ),
                View.MeasureSpec.makeMeasureSpec(
                    0,
                    View.MeasureSpec.UNSPECIFIED
                )
            )
            holder.itemView.layout(
                0,
                0,
                holder.itemView.measuredWidth,
                holder.itemView.measuredHeight
            )
            holder.itemView.isDrawingCacheEnabled = true
            holder.itemView.buildDrawingCache()
            val drawingCache = holder.itemView.drawingCache
            if (drawingCache != null) {
                bitmaCache.put(i.toString(), drawingCache)
            }
            //                holder.itemView.setDrawingCacheEnabled(false);
//                holder.itemView.destroyDrawingCache();
            height += holder.itemView.measuredHeight
        }
        bigBitmap =
            Bitmap.createBitmap(view.measuredWidth, height, Bitmap.Config.ARGB_8888)
        val bigCanvas = Canvas(bigBitmap)
        bigCanvas.drawColor(Color.WHITE)
        for (i in 0 until size) {
            val bitmap = bitmaCache[i.toString()]
            bigCanvas.drawBitmap(bitmap!!, 0f, iHeight.toFloat(), paint)
            iHeight += bitmap.height
            bitmap.recycle()
        }
    }
    return bigBitmap
}
Comments