Android - 對焦顯示功能

摘要:Android - 對焦顯示功能

為了按下畫面,能夠對焦,並且顯示對焦位置

找到一篇

http://www.jayrambhia.com/blog/android-touchfocus/

 

主要是在SurfaceView OnTouch事件時,

偵測到按下的動作,

並顯示DrawingView

 

    @Override
    public boolean onTouchEvent(MotionEvent ev) {        
        if(ev.getAction() == MotionEvent.ACTION_DOWN){
            float x = ev.getX();
            float y = ev.getY();
            
            Rect touchRect = new Rect(
                  (int)(x - 100), 
                  (int)(y - 100), 
                  (int)(x + 100), 
                  (int)(y + 100));
            
            final Rect targetFocusRect = new Rect(
                      touchRect.left * 2000/this.getWidth() - 1000,
                      touchRect.top * 2000/this.getHeight() - 1000,
                      touchRect.right * 2000/this.getWidth() - 1000,
                      touchRect.bottom * 2000/this.getHeight() - 1000);
            
            doTouchFocus(targetFocusRect);
            
            if (drawingViewSet) {
                drawingView.setHaveTouch(true, touchRect);
                drawingView.invalidate();
                
                // Remove the square after some time
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                  
                  @Override
                  public void run() {
                      drawingView.setHaveTouch(false, new Rect(0, 0, 0, 0));
                      drawingView.invalidate();
                  }
              }, 1000);
            }
            
        }
        
        return true;
    }    

 

並做一些Camera的動作上去

    /**
     * Called from PreviewSurfaceView to set touch focus.
     * 
     * @param - Rect - new area for auto focus
     */
    public void doTouchFocus(final Rect tfocusRect) {
        
        try {
            final List focusList = new ArrayList();
            Camera.Area focusArea = new Camera.Area(tfocusRect, 1000);
            focusList.add(focusArea);
          
            Camera.Parameters para = camera.getParameters();
            para.setFocusAreas(focusList);
            para.setMeteringAreas(focusList);
            camera.setParameters(para);
          
            camera.autoFocus(myAutoFocusCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

在AutoFocusCallback使用空的Callback處理

    /**
     * AutoFocus callback
     */
    AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){

          @Override
          public void onAutoFocus(boolean arg0, Camera arg1) {
           if (arg0){
               camera.cancelAutoFocus();      
           }
        }
    };

其它不足的地方,請參考連結