如何在Surfaceview上已经绘制了Camera Preview的线条上画线?

时间:2018-12-06 06:02:34

标签: android android-camera android-canvas surfaceview

当我尝试使用SurfaceChanged覆盖方法中的以下语句时,出现异常。

Canvas canvas = holder.lockCanvas();
  

异常-IllegalStateException

我的要求:我需要使用1 SurfaceView来做到这一点,而不是在其他布局中使用SurfaceView。我的目的是实时直播SurfaceView预览,并使用画布在其上绘制一条线。

1 个答案:

答案 0 :(得分:0)

以任何父级布局之一添加表面视图

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/control"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SurfaceView
        android:id="@+id/surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</RelativeLayout>

我已经创建了用于叠加摄像机的框

public class Box extends View {
    private Paint paint = new Paint();

    Box(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) { // Override the onDraw() Method
        super.onDraw(canvas);

        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(2);

        //center
        int x0 = canvas.getWidth() / 2;
        int y0 = canvas.getHeight() / 2;
        int dx = (int) (canvas.getWidth() / 2.5);
        int dy = (int) (canvas.getHeight() / 2.9);
        //draw guide box
        canvas.drawRect(x0 - dx, y0 - dy, x0 + dx, y0 + dy, paint);
    }
}

现在将此框添加到父版面中,这样它就不会更新我的表面

        Box box = new Box(this);
        relativeLayout = findViewById(R.id.control);
        relativeLayout.addView(box, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));