Android: Overlay on Android Camera Preview

后端 未结 6 571
后悔当初
后悔当初 2020-11-27 13:32

I\'m using Camera API and invoking the camera.

I want to display a header (for branding) on the top of the camera preview. The header is a jpeg image.

Is

6条回答
  •  醉梦人生
    2020-11-27 14:05

    You can use SurfaceView and create a CustomView that will open the camera and you can adjust its size in the xml accordingly. Below is a pseudo code.

    Create a class that extends SurfaceView and open camera inside that

    CapturePreview.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();
        }
        /***
         * 
         *  Take a picture and and convert it from bytes[] to Bitmap.
         *  
         */
        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);
        }
    }
    

    Now you have to include the view that you created using SurfaceView in your xml like this

    main.xml

    
    
    
      
    
      
      
    
      
    
      
    
      
        
    
    
    

    Now you can use this main.xml in any Acitivty that will open a camera with a ImageView. Thanks....

提交回复
热议问题