在Android中,PreviewView
是一個用于預覽相機捕獲的圖像或視頻的視圖。要設置PreviewView
,請按照以下步驟操作:
build.gradle
文件中添加CameraX庫的依賴項(如果尚未添加):dependencies {
implementation 'androidx.camera:camera-core:1.0.0'
implementation 'androidx.camera:camera-preview:1.0.0'
implementation 'androidx.camera:camera-camera2:1.0.0'
}
activity_main.xml
)中添加PreviewView
元素:<androidx.camera.core.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.java
)中,初始化PreviewView
并設置相機預覽:import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.SurfaceTextureProvider;
import androidx.camera.core.VideoCapture;
import androidx.camera.core.VideoCaptureConfig;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.compose.ui.platform.LocalContext;
import androidx.compose.material3.Text;
import androidx.compose.runtime.Composable;
import androidx.compose.ui.unit.dp;
import androidx.compose.ui.window.DialogWindowState;
import com.google.common.util.concurrent.ListenableFuture;
public class MainActivity extends AppCompatActivity {
private PreviewView previewView;
private ProcessCameraProvider cameraProviderFuture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView = findViewById(R.id.previewView);
// Configure the camera and preview
configureCamera(previewView);
}
private void configureCamera(PreviewView previewView) {
// Obtain an instance of the camera provider
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
// Select an appropriate camera and its configuration
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
// Create a preview configuration
PreviewConfig previewConfig = new PreviewConfig.Builder().build();
// Create a preview
Preview preview = new Preview(previewConfig);
// Attach the preview to the preview view
previewView.setSurfaceProvider(preview.getSurfaceProvider());
// Set up video capture
VideoCaptureConfig videoCaptureConfig = new VideoCaptureConfig.Builder()
.set三腳架Mode(VideoCaptureConfig.三腳架Mode.OFF)
.build();
VideoCapture videoCapture = cameraProvider.createVideoCapture(videoCaptureConfig);
// Bind the video capture to the preview
preview.setSurfaceProvider(videoCapture.getSurfaceProvider());
} catch (Exception e) {
e.printStackTrace();
}
}, ContextCompat.getMainExecutor(this));
}
}
這個示例展示了如何設置PreviewView
以預覽相機捕獲的圖像和視頻。請注意,這個示例使用了CameraX庫,它是Android Jetpack的一部分,用于簡化相機功能的實現。