ภาพรวม
ตัวอย่างนี้แสดงวิธีทำให้ SurfaceView มีพื้นหลังโปร่งใส (Transparent) เพื่อให้สามารถวาง View อื่นๆ ทับได้ เช่น วาง ImageView เป็นมาสก์ (Mask) ทับ SurfaceView ของกล้อง
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกข้อมูลที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<SurfaceView
android:id="@+id/cameraSurface"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/IV_MASK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/mask"
android:background="@android:color/transparent"/>
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ตั้งค่า SurfaceView ให้โปร่งใส
// ต้องตั้งค่าในโค้ด Java ด้วย (ไม่ได้ใน XML)
// surfaceView.setZOrderOnTop(true);
// surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);
}
}
ขั้นตอนสำคัญ: ตั้งค่า SurfaceView ให้โปร่งใสในโค้ด
ใน onCreate() ให้เพิ่มโค้ดต่อไปนี้หลัง setContentView:
import android.graphics.PixelFormat; import android.view.SurfaceView; SurfaceView surfaceView = findViewById(R.id.cameraSurface); surfaceView.setZOrderOnTop(true); // วาง SurfaceView ชั้นบนสุด surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT); // ตั้งค่าโปร่งใส
ขั้นตอนที่ 4: กำหนดค่า Manifest (Manifests/AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.sample">
<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>
การทดสอบ
เตรียมรูปภาพ mask.png ใน res/drawable/ แล้วเชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิก Run - จะเห็น ImageView ทับ SurfaceView ได้อย่างชัดเจน