androidandroid-layoutkotlinandroid-bitmap

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


I have an imageView and several textViews My app allows user to drag textViews on evey coordinates of imageView (imageView is not full screen) that user wants .

In other words this app allows user to add several captions to user image and convert that image and captions to a single image and store it on user device.

According to one of stackOverFlow responses I can just convert one textView text to a bitamp

id there any way to screenshot from final image which user have created with its captions in kotlin??

This is my code:

@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()
}

Solution

  • Add desired views in xml layout inflate it and take screenshot of parent layout that is containing your views.

    Code for taking screenshoot:

     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
    }