यह उदाहरण दर्शाता है कि Kotlin का उपयोग करके Android में वर्तमान स्क्रीन का स्क्रीनशॉट प्रोग्रामेटिक रूप से कैसे लिया जाए।
चरण 1 - नया प्रोजेक्ट बनाएं
Android Studio में File → New Project।
चरण 2 - activity_main.xml लेआउट
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnScreenshot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="स्क्रीनशॉट लें" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/btnScreenshot"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:scaleType="fitCenter" />
</RelativeLayout>
चरण 3 - MainActivity.kt में स्क्रीनशॉट लॉजिक
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
private lateinit var rootView: View
private lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
rootView = findViewById(R.id.mainLayout)
imageView = findViewById(R.id.imageView)
val btnScreenshot = findViewById<Button>(R.id.btnScreenshot)
btnScreenshot.setOnClickListener {
val bitmap = takeScreenshotOfRootView(rootView)
imageView.setImageBitmap(bitmap)
rootView.setBackgroundColor(Color.parseColor("#999999"))
}
}
companion object {
private fun takeScreenshot(view: View): Bitmap {
view.isDrawingCacheEnabled = true
view.buildDrawingCache(true)
val bitmap = Bitmap.createBitmap(view.drawingCache)
view.isDrawingCacheEnabled = false
return bitmap
}
fun takeScreenshotOfRootView(view: View): Bitmap {
return takeScreenshot(view.rootView)
}
}
}
चरण 4 - AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.screenshotdemo">
<application ...>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ऐप चलाएं
ऐप चलाएं, "स्क्रीनशॉट लें" बटन दबाएं। वर्तमान स्क्रीन का स्क्रीनशॉट ImageView में प्रदर्शित होगा और पृष्ठभूमि ग्रे हो जाएगी।
नोट:drawingCacheAPI डिप्रिकेटेड है। आधुनिक ऐप्स के लिएPixelCopyAPI याView.drawToBitmap()(API 29+) का उपयोग करने की सलाह दी जाती है।