Android截圖和指定View生成截圖分享

萬合天宜發表於2018-10-12

做專案開發過程中有遇到過根據使用者行為動態生成圖片進行分享的需求,當時因為後端有大神,這個活就被大神給攬走了。後端是使用JavaAPI進行繪製的,具體的細節不清楚,但是實現起來也是挺難的。

後來大神溜了,新的活只能自己攬下來了。據我所知Android端的View是可以生成圖片的,但是具體的細節不是很清楚,在網上查詢了很多Demo,研究了一陣時間,重新整理記錄下來。

當前頁面截圖(擷取整個螢幕)

擷取當前Activity頁面的截圖,可以通過窗體最底層的decorView進行快取,然後根據這個快取物件生成一張圖片。有的需要不需要狀態列,也可以指定生成圖片的寬高,把狀態列去除。

/**
 * 擷取當前窗體的截圖,根據[isShowStatusBar]判斷是否包含當前窗體的狀態列
 * 原理是獲取當前窗體decorView的快取生成圖片
 */
fun captureWindow(activity: Activity, isShowStatusBar: Boolean): Bitmap? {
    // 獲取當前窗體的View物件
    val view = activity.window.decorView
    view.isDrawingCacheEnabled = true
    // 生成快取
    view.buildDrawingCache()

    val bitmap = if (isShowStatusBar) {
        // 繪製整個窗體,包括狀態列
        Bitmap.createBitmap(view.drawingCache, 0, 0, view.measuredWidth, view.measuredHeight)
    } else {
        // 獲取狀態列高度
        val rect = Rect()
        view.getWindowVisibleDisplayFrame(rect)
        val display = activity.windowManager.defaultDisplay

        // 減去狀態列高度
        Bitmap.createBitmap(view.drawingCache, 0,
                rect.top, display.width, display.height - rect.top)
    }

    view.isDrawingCacheEnabled = false
    view.destroyDrawingCache()

    return bitmap
}
複製程式碼

擷取常用的View(TextView,RelativeLayout...)

擷取之前一定要View已經繪製完畢了,所以要注意使用post方法確保View繪製完畢。有的分享出去的截圖頁面並不是當前展示給使用者的UI樣式,所以可以在當前佈局中隱藏一個容器,專門用來存放截圖,這個容器不展示給使用者。

/**
  * View已經在介面上展示了,可以直接獲取View的快取
  * 對View進行量測,佈局後生成View的快取
  * View為固定大小的View,包括TextView,ImageView,LinearLayout,FrameLayout,RelativeLayout等
  * @param view 擷取的View,View必須有固定的大小,不然drawingCache返回null
  * @return 生成的Bitmap
  */
fun captureView(view: View): Bitmap? {
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache()
        // 重新測量一遍View的寬高
        view.measure(View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(view.height, View.MeasureSpec.EXACTLY))
        // 確定View的位置
        view.layout(view.x.toInt(), view.y.toInt(), view.x.toInt() + view.measuredWidth,
                view.y.toInt() + view.measuredHeight)
        // 生成View寬高一樣的Bitmap
        val bitmap = Bitmap.createBitmap(view.drawingCache, 0, 0, view.measuredWidth,
                view.measuredHeight)
        view.isDrawingCacheEnabled = false
        view.destroyDrawingCache()
        return bitmap
}
複製程式碼

擷取ScrollView

ScrollView截圖的難點在於ScrollView高度不確定,如果能確定高度,就可以使用ScrollView的快取生成圖片。ScrollView只有一個子View,所以只需要對子View進行測量,獲取到子View的高度就可以確定ScrollView的高度。

/**
 * 擷取ScrollerView
 * 原理是獲取scrollView的子View的高度,然後建立一個子View寬高的畫布,將ScrollView繪製在畫布上
 * @param scrollView 控制元件
 * @return 返回截圖後的Bitmap
 */
fun captureScrollView(scrollView: ScrollView): Bitmap? {
     var h = 0
     for (i in 0 until scrollView.childCount) {
         val childView = scrollView.getChildAt(i)
         // 獲取子View的高度
         h += childView.height
         // 設定背景顏色,避免佈局裡未設定背景顏色,截的圖背景黑色
         childView.setBackgroundColor(Color.parseColor("#FFFFFF"))
     }

     val bitmap = createBitmap(scrollView.width, h)
     val canvas = Canvas(bitmap)
     // 將ScrollView繪製在畫布上
     scrollView.draw(canvas)
     return bitmap
}
複製程式碼

擷取ListView

ListView截圖原理是獲取到每一個子View的Bitmap物件,然後根據子View的高度,使用Paint將子View的截圖拼接繪製到Canvas上,最後生成一張包含所有子View的截圖。

/**
 * 擷取ListView
 * 原理:獲取到每一個子View,將子View生成的bitmap存入集合,並且累積ListView高度
 * 遍歷完成後,建立一個ListView大小的畫布,將集合的Bitmap繪製到畫布上
 * @param listView 截圖控制元件物件
 * @return 生成的截圖物件
 */
fun captureListView(listView: ListView): Bitmap? {
        val adapter = listView.adapter
        val itemCount = adapter.count
        var allitemsheight = 0
        val bitmaps = ArrayList<Bitmap>()

        for (i in 0 until itemCount) {
            // 獲取每一個子View
            val childView = adapter.getView(i, null, listView)
            // 測量寬高
            childView.measure(
                    View.MeasureSpec.makeMeasureSpec(listView.width, View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))

            // 佈局位置
            childView.layout(0, 0, childView.measuredWidth, childView.measuredHeight)
            // 設定背景顏色,避免是黑色的
            childView.setBackgroundColor(Color.parseColor("#FFFFFF"))
            childView.isDrawingCacheEnabled = true
            // 生成快取
            childView.buildDrawingCache()
            // 將每一個View的截圖加入集合
            bitmaps.add(childView.drawingCache)
            // 疊加截圖高度
            allitemsheight += childView.measuredHeight
        }

        // 建立和ListView寬高一樣的畫布
        val bitmap = createBitmap(listView.measuredWidth, allitemsheight)
        val canvas = Canvas(bitmap)

        val paint = Paint()
        var iHeight = 0f

        for (i in bitmaps.indices) {
            val bmp: Bitmap = bitmaps[i]
            // 將每一個生成的bitmap繪製在畫布上
            canvas.drawBitmap(bmp, 0f, iHeight, paint)
            iHeight += bmp.height

            bmp.recycle()
        }
        return bitmap
}
複製程式碼

擷取RecyclerView

RecyclerView截圖和ListView截圖原理一樣,都是將子View的截圖進行拼接,最後生成一張大的截圖。

/**
 * 擷取RecyclerView
 * 原理和ListView集合是一樣的,獲取到每一個Holder的截圖放入集合,最後統一繪製到Bitmap上
 * @param recyclerView&emsp;要截圖的控制元件
 * @return 生成的截圖
 */
fun captureRecyclerView(recyclerView: RecyclerView): Bitmap? {
        val adapter = recyclerView.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 bitmapCache = LruCache<String, Bitmap>(cacheSize)
            for (i in 0 until size) {
                val holder = adapter.createViewHolder(recyclerView, adapter.getItemViewType(i))
                adapter.onBindViewHolder(holder, i)
                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(recyclerView.width, View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
                holder.itemView.layout(0, 0, holder.itemView.measuredWidth,
                        holder.itemView.measuredHeight)
                holder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"))
                holder.itemView.isDrawingCacheEnabled = true
                holder.itemView.buildDrawingCache()
                val drawingCache = holder.itemView.drawingCache
                if (drawingCache != null) {
                    bitmapCache.put(i.toString(), drawingCache)
                }
                height += holder.itemView.measuredHeight
            }

            bigBitmap = createBitmap(recyclerView.measuredWidth, height)
            val bigCanvas = Canvas(bigBitmap!!)
            val lBackground = recyclerView.background
            if (lBackground is ColorDrawable) {
                val lColor = lBackground.color
                bigCanvas.drawColor(lColor)
            }

            for (i in 0 until size) {
                val bitmap = bitmapCache.get(i.toString())
                bigCanvas.drawBitmap(bitmap, 0f, iHeight.toFloat(), paint)
                iHeight += bitmap.height
                bitmap.recycle()
            }
        }
        return bigBitmap
}
複製程式碼

擷取WebView

WebView可以載入很長很複雜的頁面,所以進行截圖很容易發生記憶體溢位,不過一般的需求也不會有那個大的圖片去分享,這裡只做簡單的截圖。

/**
 * 擷取WebView,包含WebView的整個長度
 * 在WebView渲染之前要加上以下程式碼,開啟Html快取,不然會截圖空白
 *  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 *      WebView.enableSlowWholeDocumentDraw()
 *  }
 *  WebView的截圖很容易遇到記憶體溢位的問題,因為WebView可以載入很多內容,導致生成的圖片特別長,建立Bitmap時容易OOM
 */
fun captureWebView(webView: WebView): Bitmap? {
        //&emsp;重新呼叫WebView的measure方法測量實際View的大小(將測量模式設定為UNSPECIFIED模式也就是需要多大就可以獲得多大的空間)
        webView.measure(View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        //&emsp;呼叫layout方法設定佈局(使用新測量的大小)
        webView.layout(0, 0, webView.measuredWidth, webView.measuredHeight)
        //&emsp;開啟WebView的快取(當開啟這個開關後下次呼叫getDrawingCache()方法的時候會把view繪製到一個bitmap上)
        webView.isDrawingCacheEnabled = true
        //&emsp;強制繪製快取(必須在setDrawingCacheEnabled(true)之後才能呼叫,否者需要手動呼叫destroyDrawingCache()清楚快取)
        webView.buildDrawingCache()

        val bitmap = createBitmap(webView.measuredWidth, webView.measuredHeight)

        //&emsp;已picture為背景建立一個畫布
        val canvas = Canvas(bitmap)  // 畫布的寬高和 WebView 的網頁保持一致
        val paint = Paint()
        //&emsp;設定畫筆的定點位置,也就是左上角
        canvas.drawBitmap(bitmap, 0f, webView.measuredHeight * 1f, paint)
        //&emsp;將WebView繪製在剛才建立的畫板上
        webView.draw(canvas)
        webView.isDrawingCacheEnabled = false
        webView.destroyDrawingCache()
        return bitmap
}
複製程式碼

基本常用的View都可以進行截圖,但是像WebView這種可以載入很長很複雜頁面的控制元件,截圖容易發生OOM,所以要考慮好用什麼控制元件進行截圖。上面的程式碼親測都可以使用。

專案地址

相關文章