Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidアプリのスクリーンショットをプログラム的に撮影する方法

この記事では、Kotlinを使用してAndroidアプリ内からプログラム的にスクリーンショット(画面キャプチャ)を撮影する方法を解説します。サンプルでは、ボタンをタップすると現在表示中の画面全体がBitmapとして取得され、ImageViewにその結果が表示される仕組みになっています。

手順1:新しいプロジェクトを作成する

Android Studioを開き、「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。

手順2:レイアウトファイル(activity_main.xml)の実装

res/layout/activity_main.xml に以下のコードを追加します。画面上部にスクリーンショット撮影用のButton、その下に撮影結果を表示するためのImageViewを配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    style="?attr/actionButtonStyle"
    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 の実装

src/MainActivity.kt に以下のコードを追加します。ここでのポイントは、companion object 内に定義した Screenshot オブジェクトです。Viewの描画キャッシュ(Drawing Cache)を一時的に有効化してBitmapを生成しており、rootView を対象にすることで画面全体をキャプチャできます。

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 main: View
    private lateinit var imageView: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        main = findViewById(R.id.main)
        imageView = findViewById(R.id.imageView)
        val btn: Button = findViewById(R.id.button)
        btn.setOnClickListener {
            val b: Bitmap = Screenshot.takeScreenshotOfRootView(imageView)
            imageView.setImageBitmap(b)
            main.setBackgroundColor(Color.parseColor("#999999"))
        }
    }
    companion object Screenshot {
        private fun takeScreenshot(view: View): Bitmap {
            view.isDrawingCacheEnabled = true
            view.buildDrawingCache(true)
            val b = Bitmap.createBitmap(view.drawingCache)
            view.isDrawingCacheEnabled = false
            return b
        }
        fun takeScreenshotOfRootView(v: View): Bitmap {
            return takeScreenshot(v.rootView)
        }
    }
}

注意: isDrawingCacheEnableddrawingCache などの描画キャッシュ関連APIは、API 28(Android 9.0)以降で非推奨(Deprecated)となっています。最新の環境で開発する場合は、PixelCopy APIやCanvasへの再描画による取得など、代替手法の採用を検討してください。

手順4:AndroidManifest.xml の設定

androidManifest.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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>

アプリの実行と動作確認

それでは、実際にアプリを実行してみましょう。ここでは、実機のAndroid端末をパソコンに接続しているものとして説明を進めます。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。接続したモバイル端末を選択してアプリを起動すると、以下のような初期画面が表示されます。

KotlinでAndroidアプリのスクリーンショットをプログラム的に撮影する方法

「Take screenshot」ボタンをタップすると、現在の画面のスクリーンショットが撮影され、背景色がグレーに変化するとともに、ImageView上にキャプチャ画像が表示されます。これで、Kotlinだけで画面キャプチャ機能を実装できました。

  1. 【Android開発】プログラムからスクリーンショットを撮影する方法をステップ解説

    この記事では、Androidアプリ内からプログラム的にスクリーンショットを撮影する方法を、実際のコード例とともに段階的に解説します。Viewの描画キャッシュ機能を利用することで、特別な権限なしに画面のBitmap画像を取得できます。全体の流れ実装は以下の5つのステップで行います。Android Studioで新規プロジェクトを作成するレイアウトファイル(activity_main.xml)を編集するスクリーンショット取得用のJavaクラスを作成するMainActivity.javaにボタンの処理を実装するAndroidManifest.xmlを確認するステップ1:新規プロジェクトの作成まず、A

  2. Androidアプリでカメラを使ってプログラムから写真を撮影する方法【サンプルコード付き】

    この記事では、Androidアプリからカメラを起動し、プログラムによって写真を撮影・表示する方法を、実際のコード例とともに段階的に解説します。ボタンをタップすると標準カメラアプリが起動し、撮影した画像をImageViewに表示するシンプルなサンプルです。全体の流れ今回の実装では、以下の手順でカメラ撮影機能を構築します。Android Studioで新規プロジェクトを作成するレイアウトファイル(activity_main.xml)にUIを定義するMainActivity.javaにカメラ起動と結果受け取りの処理を書くAndroidManifest.xmlにカメラ権限を追加するステップ1:新規プロ