Android 摄像头圆形预览框
时间: 2023-08-05 21:53:17 浏览: 126
要在 Android 摄像头预览中显示圆形预览框,可以通过以下步骤实现:
1. 创建一个自定义 View,用于显示预览数据和圆形预览框。
2. 在自定义 View 中重写 onDraw 方法,在画布上绘制一个圆形预览框。
3. 在 Camera.PreviewCallback 中获取预览数据,并将其绘制到自定义 View 上。
4. 将自定义 View 添加到布局中。
以下是示例代码:
```java
public class CirclePreviewView extends View implements Camera.PreviewCallback {
private Paint mCirclePaint;
private byte[] mPreviewData;
private Camera mCamera;
public CirclePreviewView(Context context) {
super(context);
init();
}
public CirclePreviewView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mCirclePaint = new Paint();
mCirclePaint.setColor(Color.WHITE);
mCirclePaint.setStyle(Paint.Style.STROKE);
mCirclePaint.setStrokeWidth(5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(centerX, centerY) - 10;
canvas.drawCircle(centerX, centerY, radius, mCirclePaint);
if (mPreviewData != null) {
YuvImage yuvImage = new YuvImage(mPreviewData, ImageFormat.NV21, getWidth(), getHeight(), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, getWidth(), getHeight()), 100, out);
byte[] jpegData = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length);
canvas.drawBitmap(bitmap, null, new RectF(0, 0, getWidth(), getHeight()), null);
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
mPreviewData = data;
invalidate();
}
public void setCamera(Camera camera) {
mCamera = camera;
mCamera.setPreviewCallback(this);
}
}
```
在布局文件中添加自定义 View:
```xml
<com.example.CirclePreviewView
android:id="@+id/circle_preview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
在 Activity 中获取 Camera 实例,并将其设置给自定义 View:
```java
Camera camera = Camera.open();
CirclePreviewView previewView = findViewById(R.id.circle_preview);
previewView.setCamera(camera);
```
注意:在 Android 5.0 及以上版本中,Camera 已被废弃,应使用 Camera2 API。
阅读全文