如何在相机应用程序中添加矩形叠加?

问题描述 投票:7回答:2

如何在相机预览中添加矩形叠加(应该更像矩形框)?我的应用程序包含一个按钮,可在单击时打开相机。我需要相机预览中的叠加层。

java文件的代码是:

    public class MainActivity extends Activity {
     Button b;
     Intent i;
     Bitmap bmp;
     final static int cameraData = 0;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         b = (Button) findViewById(R.id.button);
         InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
         bmp = BitmapFactory.decodeStream(is);
         b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
            // TODO Auto-generated method stub
            i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(i, cameraData);

        }
    });
 }
}

布局文件如下:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center"
    android:text="click to take photo" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="click"
    android:layout_gravity="center" />

</LinearLayout>
android overlay android-camera
2个回答
5
投票

您必须通过扩展SurfaceView类来创建自己的预览。

请参阅以下链接,以帮助您。

Custom camera android

将SurfaceLayout与SurfaceView一起作为child.and根据您的需要进行自定义


19
投票

首先,创建一个扩展View的公共类。在它的onDraw()方法中,绘制你的矩形。例如:

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(10);

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

然后,在您的相机预览活动中,为您的Box类添加一个实例:

Box box = new Box(this);

最后:

addContentView(box, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

将在相机预览上绘制绿色矩形。

© www.soinside.com 2019 - 2024. All rights reserved.