什么是最简单的方法来获取屏幕截图在android使用Kotlin?

cnh2zyt3  于 2022-11-03  发布在  Android
关注(0)|答案(2)|浏览(287)

我有一个imageView和几个textView我的应用程序允许用户在imageView的每个坐标上拖动textView**(imageView不是全屏)
换句话说,这个应用程序允许用户添加几个标题到用户图像,并将该图像和标题转换为一个
单一图像,并存储在用户设备上。
根据其中一个
stackOverFlow响应,我只能将一个textView**文本转换为位放大器
有没有办法从最终的图像截图,用户已经创建了它的标题在Kotlin??
这是我的代码:

@Throws(IOException::class)
fun foo(text: String) {
    val textPaint = object : Paint() {
        init {
            setColor(Color.WHITE)
            setTextAlign(Align.CENTER)
            setTextSize(20f)
            setAntiAlias(true)

        }
    }
    val bounds = Rect()
    textPaint.getTextBounds(text, 0, text.length, bounds)

    val bmp = Bitmap.createBitmap(mImgBanner.getWidth(), mImgBanner.getHeight(), Bitmap.Config.RGB_565) //use ARGB_8888 for better quality
    val canvas = Canvas(bmp)
    canvas.drawText(text, 0, 20f, textPaint)
    val path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/image.png"
    val stream = FileOutputStream(path)
    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream)
    bmp.recycle()
    stream.close()
}
atmip9wb

atmip9wb1#

在xml布局中添加所需的视图,并对包含您的视图的父布局进行截图。
截图代码:

fun takeScreenshotOfView(view: View, height: Int, width: Int): Bitmap {
            val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            val bgDrawable = view.background
            if (bgDrawable != null) {
                bgDrawable.draw(canvas)
            } else {
                canvas.drawColor(Color.WHITE)
            }
            view.draw(canvas)
            return bitmap
        }
avwztpqn

avwztpqn2#

您也可以使用扩展名View.drawToBitmap()。它将返回一个位图

/**
 * Return a [Bitmap] representation of this [View].
 *
 * The resulting bitmap will be the same width and height as this view's current layout
 * dimensions. This does not take into account any transformations such as scale or translation.
 *
 * Note, this will use the software rendering pipeline to draw the view to the bitmap. This may
 * result with different drawing to what is rendered on a hardware accelerated canvas (such as
 * the device screen).
 *
 * If this view has not been laid out this method will throw a [IllegalStateException].
 *
 * @param config Bitmap config of the desired bitmap. Defaults to [Bitmap.Config.ARGB_8888].
 */
fun View.drawToBitmap(config: Bitmap.Config = Bitmap.Config.ARGB_8888): Bitmap {
    if (!ViewCompat.isLaidOut(this)) {
        throw IllegalStateException("View needs to be laid out before calling drawToBitmap()")
    }
    return Bitmap.createBitmap(width, height, config).applyCanvas {
        translate(-scrollX.toFloat(), -scrollY.toFloat())
        draw(this)
    }
}

相关问题