如何在 Android 中以程式設計方式擷取螢幕截圖?
此示例演示瞭如何在 Android 中以程式設計方式擷取螢幕截圖。
步驟 1 - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟 2 - 將以下程式碼新增到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/parent" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:background="#33FFFF00" android:orientation="vertical"> <ImageView android:id="@+id/screenShot" android:layout_width="300dp" android:layout_height="300dp" /> <TextView android:id="@+id/text" android:textSize="18sp" android:layout_gravity="center" android:text="Click" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
在上面的程式碼中,我們使用了兩個檢視作為 ImageView 和 TextView。當用戶點選 TextView 時,它將擷取螢幕截圖並附加到 ImageView 中。
步驟 3 - 將以下程式碼新增到 src/MainActivity.java 中
package com.example.andy.myapplication; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int view=R.layout.activity_main; ImageView screenShort; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); final LinearLayout parent=findViewById(R.id.parent); screenShot=findViewById(R.id.screenShot); textView=findViewById(R.id.text); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setText("It is screen shot text"); screenShot(parent); } }); } public void screenShot(View view) { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); screenShot.setImageBitmap(bitmap); textView.setText("click"); } }
在上面的程式碼中,我們編寫了 screenshot(view) 方法,在這個方法中,我們傳遞了父檢視以從頂部到底部擷取螢幕截圖。要擷取螢幕,請使用以下程式碼 -
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); screenShort.setImageBitmap(bitmap);
讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的電腦。要從 Android Studio 執行應用程式,請開啟您專案中的一個 Activity 檔案,然後單擊執行 工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -
現在點選 TextView,它將擷取螢幕截圖並附加到 ImageView 中,如下所示 -
點選此處下載專案程式碼
廣告