1. 程式人生 > >android camera2 api點選圖片實現聚焦

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<Camera.Area> mylist = new ArrayList<Camera.Area>();
                        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:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="xxx.FirstICActivity">
    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/frame"
        android:contentDescription="" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:clickable="true"
        android:onClick="takepic"
        android:text="Capture"
        android:textColor="#ffffff"
        android:textSize="23sp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:clickable="true"
        android:onClick="icBack"
        android:text="Next"
        android:textColor="#ffffff"
        android:textSize="23sp" />


    <ImageView
        android:id="@+id/iv_pic"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:layout_alignParentEnd="true"
        android:contentDescription="" />
</RelativeLayout>





預覽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 camera2 api圖片實現聚焦

public class FirstICActivity extends AppCompatActivity { private static final String TAG = "TestCamera"; private Camera mCamer

android:多次效果實現

public class MainActivity extends AppCompatActivity{ private final static int COUNTS = 5;//點選次數 private final static long VALIDTIME = 1300;/

Android 按鈕的事件實現1

在xml檔案中建立一個Button,新增一個onClick屬性, <Button      android:layout_width="wrap_content"     android:layout_height="wrap_content"     android

android 關於WebView圖片展示大圖

最近因為專案的需要 在載入webview的時候如果有圖片展示點選能夠檢視大圖,剛開始百思不得其解,後來經過多方的努力得以實現。 這一行程式碼是為了重寫js互動 webView.setWebViewClient(new MyWebViewClient(co

Android:通過濾鏡實現圖片變暗效果

package com.linj.camera.view; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.gra

Android 實現WebView圖片檢視大圖列表及圖片儲存

在日常開發過程中,有時候會遇到需要在app中嵌入網頁,此時使用WebView實現效果,但在預設情況下是無法點選圖片檢視大圖的,更無法儲存圖片。本文將就這一系列問題的實現進行說明。 圖示: 專案的知識點: 載入網頁後如何捕捉網頁中的圖片點選事件; 獲取點選

thinkPHP5.0框架驗證碼呼叫及圖片重新整理簡單實現方法

這篇文章主要介紹了thinkPHP5.0框架驗證碼呼叫及點選圖片重新整理簡單實現方法,結合簡單示例形式分析了thinkPHP5框架驗證碼相關配置、後臺驗證、前臺重新整理等操作技巧,學習 thinkphp原始碼的朋友可以參考下,具體如下:   1、配置檔案中

Android RecyclerView事件實現的兩種方式

因為經常會用到RecyclerView,今天在這裡總結一下實現RecyclerView點選事件的實現方法 一、通過介面回撥的方式實現     1. 首先定義一個點選的介面(Recyclerview自身不帶有點選事件的回撥) public interface OnRec

Android RecyclerView事件實現的幾種方式

因為經常會用到RecyclerView,今天在這裡總結一下實現RecyclerView點選事件的實現方法 一、通過介面回撥的方式實現     1. 首先定義一個點選的介面(Recyclerview自身不帶有點選事件的回撥) public interface OnRec

vue實現圖片放大圖片

### 使用vue一個元件vue-directive-image-previewer A Vue.js project for tag img, click img to zoom out to ful

簡單實現圖片放大的功能

背景:想在app中加上點選縮圖放大的效果,但是不想匯入大量的JS ,也無需哪些複雜的外掛,於是自己手寫了一個很簡單的實現,在這裡記下來。 程式碼很簡單,還有很多優化空間,時間有限,就沒有優化了 1 . 先準備大圖的位置 大圖是fixed於整個介面,只修改其中的s

layui 上傳圖片回顯並放大實現

1、頁面程式碼佈局 <div class="layui-col-xs12 form-group"> <div class="layui-col-xs6"> <div class="

ASP.NET中怎樣實現圖片驗證碼功能,並且圖片會重新整理

------ 基本思路: 圖片的src=後臺的一個函式,此函式返回按照一定規則生成的圖片檔案流。 然後此圖片即可生成。 那麼怎樣重新整理驗證碼呢,這是個問題。 因為給圖片的src賦了值之後,想要更換一個圖片,那麼src的那個函式必須再執行一次才行。 <img src=

Android 按鈕實現控制元件顯示隱藏

我寫了一個自定義的listview,listview 每一列點選切換圖示 同時顯示 隱藏的佈局,再次點選則隱藏該佈局。以下是判斷的程式碼: holder.isShowlin.setOnClickListener(new View.OnClickListener() { @

HTML 圖片更換驗證碼的實現

有一些的網站的需要圖片驗證碼當你點選的時候可以變換驗證碼 <img style="height: 22px;" id="codeImg" onclick="this.src='verifycode?'+Math.random()"alt="點選更換" t

Android SeekBar 禁止拖動和實現(可能是最簡單完美的實現

在播放線上音訊時,需求是不能拖動進度條,讓音訊自然播放。 實現就很簡單了,不要和網上的那樣重寫onTouchEvent,沒有必要的,所以一定要了解Android的觸控機制。 直接監聽SeekBar

詳解Android中回撥機制與RecyclerView的Item事件實現

總是看書上寫著回調回調,以為就是函式呼叫換了個名字,尤其是看了Button的點選事件實現後,覺得不就是觸發機制。 A事件發生->後臺處理邏輯->告訴前臺怎麼做->結束。 Android常見button點選事件: loginB

HTML:如何圖片上的某個實現對映連結

廢話不多說,附上程式碼 <img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap"> <map name="planetmap">   <area

iOS 實現圖片放大&長按儲存圖片

一:簡介 在專案中免不了會遇到,實名認證上傳身份證、繫結銀行卡等功能。在實際操作中呢,會涉及到上傳圖片,在頁面佈局時,可能圖片不是一張,考慮到佈局的美觀等因素,顯示圖片的位置變得很小,如果想檢視上傳的圖片是否清晰,內容是否完整,可能就需要放大才能實現,下面就和大家分享一下我封裝的一類,完美的

jq實現容器實現2張圖片切換(改變src路徑)

實現點選一個容器實現圖片切換的方法有很多,本篇為使用jquery實現點選圖片,實現在2張圖片來回切換。思路為: 1.點選某個容器觸發事件,事件對要處理的目標進行判斷。 2.判斷如果當前某處的圖片的src等於要切換的圖片的src,則讓src等於第二張圖片的路徑。 3.如果當前