Android积木之图片的生成和保存

 private fun generationPic(callback: (response: List) -> Unit) {


        Observable.just(selectList)
                .map {
                    val response = ArrayList()
                    for (i in 0 until selectList.size) {

                        val outMetrics = DisplayMetrics()
                        windowManager.defaultDisplay.getMetrics(outMetrics)
                        val widthPixels = outMetrics.widthPixels
                        val heightPixels = widthPixels*814/375

                        var shareOrderView = ShareOrderView(this)
                        shareOrderView.orderItem=selectList[i].orderItem
                        layoutView(shareOrderView,widthPixels,heightPixels)
                        var bitmap = loadBitmapFromView(shareOrderView)
                        if (bitmap == null) {
                            continue
                        }
                        val joinPath = Config.SAVE_REAL_PATH + "share_order_" + System.currentTimeMillis()
                        FileUtil.saveImageToSDCard(bitmap, 100, joinPath)

                        response.add(ScreenShotResponse(joinPath, System.currentTimeMillis(), widthPixels.toLong(), heightPixels.toLong()))
                    }
                    response
                }
//                .toList(shareOrderView)
                .subscribeOn(RxUtils.getSchedulerIO())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    callback(it)
                }, {
                    it.printStackTrace()
                })
    }

private fun loadBitmapFromView(v: View): Bitmap {
        var w = v.width

        var h = v.height

        var bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)

        var c = Canvas(bmp)

        c.drawColor(Color.WHITE)

        v.layout(0, 0, w, h)

        v.draw(c)
        return bmp
    }


 private fun layoutView(v: View, width: Int, height: Int) {
        // 整个View的大小 参数是左上角 和右下角的坐标
        v.layout(0, 0, width, height)
        val measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY)
        val measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
        /** 当然,measure完后,并不会实际改变View的尺寸,需要调用View.layout方法去进行布局。
         * 按示例调用layout函数后,View的大小将会变成你想要设置成的大小。
         */
        v.measure(measuredWidth, measuredHeight)
        v.layout(0, 0, v.measuredWidth, v.measuredHeight)
    }

 

你可能感兴趣的:(Android积木)