ภาพรวม
ตัวอย่างนี้สาธิตวิธีการถ่ายภาพหน้าจอ (Screenshot) โดยโปรแกรมในแอป Android โดยใช้ DrawingCache และ Kotlin
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Take screenshot" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:scaleType="fitCenter" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.kt
ใช้ DrawingCache เพื่อจับภาพหน้าจอ:
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 mainView: View
private lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
mainView = findViewById(R.id.main)
imageView = findViewById(R.id.imageView)
val btn: Button = findViewById(R.id.button)
btn.setOnClickListener {
val bitmap = Screenshot.takeScreenshotOfRootView(imageView)
imageView.setImageBitmap(bitmap)
mainView.setBackgroundColor(Color.parseColor("#999999"))
}
}
companion object Screenshot {
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(v: View): Bitmap {
return takeScreenshot(v.rootView)
}
}
}
ขั้นตอนที่ 4: ตั้งค่า AndroidManifest.xml
ใช้การตั้งค่ามาตรฐาน (หมายเหตุ: โค้ดต้นฉบับมี typo ที่ `</activityv>` ควรเป็น `</activity>`)
ทดสอบการทำงาน
รันแอปบนอุปกรณ์จริง กดปุ่ม "Take screenshot" จะจับภาพหน้าจอปัจจุบันและแสดงใน ImageView
หมายเหตุ: วิธีนี้ใช้DrawingCacheซึ่งถูก Deprecated ใน API รุ่นใหม่ สำหรับแอปจริงแนะนำให้ใช้PixelCopyAPI หรือView.drawToBitmap()แทน