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

What is the simplest way to get screenshot in android using kotlin?

我有一个 imageView 和几个 textView 我的应用程序允许用户将 textViews 拖动到用户想要的 imageView (imageView 不是全屏) 的每个坐标上。

换句话说,这个应用程序允许用户为用户图像添加多个标题 并将该图像和标题转换为图像并将其存储在用户设备上。

根据 Whosebug 回复之一,我可以将一个 textView 文本转换为 bitamp

是否有任何方法可以截取用户在 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()
}

在 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
        }

您还可以使用扩展 View.drawToBitmap()。它将return一个位图

/**
 * 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)
    }
}