如何在android中的相机预览上绘制rectange

时间:2015-08-04 07:16:11

标签: android overlay qr-code

实际上我不明白如何在相机预览上实现矩形。一切运作良好,但我不知道如何放置矩形边框link。请有人帮帮我。感谢。

1 个答案:

答案 0 :(得分:3)

我建议您在自定义SurfaceView中实现相机预览,然后在XML中,您可以简单地覆盖矩形,就像这里接受的答案一样:

Android: Overlay on Android Camera Preview

所以在项目中添加一个Java文件:

public class CapturePreview extends SurfaceView implements SurfaceHolder.Callback{

    public static Bitmap mBitmap;
    SurfaceHolder holder;
    static Camera mCamera;

    public CapturePreview(Context context, AttributeSet attrs) {
    super(context, attrs);

        holder = getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {

        Camera.Parameters parameters = mCamera.getParameters();
        parameters.getSupportedPreviewSizes();
        mCamera.setParameters(parameters);
        mCamera.startPreview();
    }
    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        try {
            mCamera = Camera.open();
            mCamera.setPreviewDisplay(holder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();
    }

    public static void takeAPicture(){  

        Camera.PictureCallback mPictureCallback = new PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {

                BitmapFactory.Options options = new BitmapFactory.Options();
                mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
            }
        };
        mCamera.takePicture(null, null, mPictureCallback);
    }
}

请注意,您必须确保它具有相应的包名。

然后更改主XML文件:

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

  <[PACKAGE_NAME].CapturePreview 
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>


  <LinearLayout 
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background:"#55999999"
      android:padding:"30dp"
      android:gravity="center">

  </LinearLayout>  

</RelativeLayout>

这应该在相机预览上有一个透明的矩形。