android camera2 api点击图片实现聚焦

public class FirstICActivity extends AppCompatActivity {




    private static final String TAG = "TestCamera";
    private Camera mCamera;
    private CameraPreview mPreview;
    private ImageView ivpic;
    private FrameLayout cameraPreview;
    public static Bitmap bitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_ic);




        checkpermission();




        ivpic = findViewById(R.id.iv_pic);
        cameraPreview = (FrameLayout) findViewById(R.id.camera_preview);
        cameraPreview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mCamera != null) {
                    Camera camera = mCamera;
                    camera.cancelAutoFocus();


                    Camera.Parameters parameters = camera.getParameters();
                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);


                    if (parameters.getMaxNumFocusAreas() > 0) {
                        List mylist = new ArrayList();
                        mylist.add(new Camera.Area(new Rect(-1000, -1000, 1000, 0), 750));
                        parameters.setFocusAreas(mylist);
                    }


                    camera.setParameters(parameters);
                    camera.autoFocus(new Camera.AutoFocusCallback() {
                        @Override
                        public void onAutoFocus(boolean success, Camera camera) {
                            camera.cancelAutoFocus();
                            Camera.Parameters params = camera.getParameters();
                            if (params.getFocusMode().equals(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                                camera.setParameters(params);
                            }
                        }
                    });
                }
                return true;
            }




        });


    }




    private void checkpermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA},
                        1);
            }
        } else {
            init();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    init();
                } else {
                    checkpermission();
                }
                return;
            }
        }
    }


    private void init() {
        boolean hascamera = checkCameraHardware(this);
        if (hascamera) {
            Log.v(TAG, "HAS CAMERA");
        } else {
            Log.v(TAG, "NO CAMERA");
        }


        if (hascamera) {
            // Create an instance of Camera
            mCamera = getCameraInstance();


            if (mCamera != null) {
                // Create our Preview view and set it as the content of our activity.
                mPreview = new CameraPreview(this, mCamera);
                FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
                preview.addView(mPreview);
            } else {
                Log.v(TAG, "mCamera is null");
            }
        }
    }


    @Override
    protected void onDestroy() {
        mCamera.release();
        super.onDestroy();
    }


    public void takepic(View v) {
        if (mCamera != null) {
            mCamera.takePicture(null, null, mPicture);
        }
    }


    private Camera.PictureCallback mPicture = new Camera.PictureCallback() {


        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            ivpic = findViewById(R.id.iv_pic);
            ivpic.setImageBitmap(bitmap);
            mCamera.startPreview();
        }
    };


    /**
     * Check if this device has a camera
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }


    /**
     * A safe way to get an instance of the Camera object.
     */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        } catch (Exception e) {
            e.printStackTrace();
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }


    public void icBack(View view) {
        mCamera.stopPreview();
        mCamera.release();




        Intent intent = new Intent(FirstICActivity.this, SecondICActivity.class);
        startActivity(intent);
    }


去下一个 activity之前关闭camera

 mCamera.stopPreview();
        mCamera.release();


Layout:




    


    


    
    


    





预览Preview activity :
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
    private static final String TAG = "TestCamera";
    private SurfaceHolder mHolder;
    private Camera mCamera;


    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;


        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }


    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);




            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }


    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }


    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.


        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }


        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }


        // set preview size and make any resize, rotate or
        // reformatting changes here


        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);


            mCamera.startPreview();


        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }


你可能感兴趣的:(android,JAVA)