安卓触摸对焦
安卓触摸对焦
1. 相机坐标说明
触摸对焦需要通过setFocusAreas()
设置对焦区域,而该方法的参数的坐标,与屏幕坐标并不相同,需要做一个转换。
对Camera
(旧版相机API)来说,相机的坐标区域是一个2000*2000,原点在中心区域,该区域与相机预览画面的边界重合,如下图所示:
谷歌的文档对getFocusAreas()
方法的描述如下(文档连接):
Gets the current focus areas. Camera driver uses the areas to decide focus.
Before using this API or setFocusAreas(java.util.List), apps should call getMaxNumFocusAreas() to know the maximum
number of focus areas first. If the value is 0, focus area is not supported.Each focus area is a rectangle with specified weight. The direction is relative to the sensor orientation, that is,
what the sensor sees. The direction is not affected by the rotation or mirroring of Camera.setDisplayOrientation(int).
Coordinates of the rectangle range from -1000 to 1000. (-1000, -1000) is the upper left point. (1000, 1000) is the lower
right point. The width and height of focus areas cannot be 0 or negative.The weight must range from 1 to 1000. The weight should be interpreted as a per-pixel weight - all pixels in the area
have the specified weight. This means a small area with the same weight as a larger area will have less influence on the
focusing than the larger area. Focus areas can partially overlap and the driver will add the weights in the overlap
region.A special case of a null focus area list means the driver is free to select focus targets as it wants. For example,
the driver may use more signals to select focus areas and change them dynamically. Apps can set the focus area list to
null if they want the driver to completely control focusing.Focus areas are relative to the current field of view (getZoom()). No matter what the zoom level is, (-1000,-1000)
represents the top of the currently visible camera frame. The focus area cannot be set to be outside the current field
of view, even when using zoom.Focus area only has effect if the current focus mode is FOCUS_MODE_AUTO, FOCUS_MODE_MACRO,
FOCUS_MODE_CONTINUOUS_VIDEO, or FOCUS_MODE_CONTINUOUS_PICTURE.
同时,设置测光区域setMeteringAreas()
的方法参数的坐标,跟对焦区域的坐标是一样的,文档对getMeteringAreas()
的描述如下(文档连接):
Gets the current metering areas. Camera driver uses these areas to decide exposure.
Before using this API or setMeteringAreas(java.util.List), apps should call getMaxNumMeteringAreas() to know the
maximum number of metering areas first. If the value is 0, metering area is not supported.Each metering area is a rectangle with specified weight. The direction is relative to the sensor orientation, that is,
what the sensor sees. The direction is not affected by the rotation or mirroring of Camera.setDisplayOrientation(int).
Coordinates of the rectangle range from -1000 to 1000. (-1000, -1000) is the upper left point. (1000, 1000) is the lower
right point. The width and height of metering areas cannot be 0 or negative.The weight must range from 1 to 1000, and represents a weight for every pixel in the area. This means that a large
metering area with the same weight as a smaller area will have more effect in the metering result. Metering areas can
partially overlap and the driver will add the weights in the overlap region.A special case of a null metering area list means the driver is free to meter as it chooses. For example, the driver
may use more signals to select metering areas and change them dynamically. Apps can set the metering area list to null
if they want the driver to completely control metering.Metering areas are relative to the current field of view (getZoom()). No matter what the zoom level is, (-1000,-1000)
represents the top of the currently visible camera frame. The metering area cannot be set to be outside the current
field of view, even when using zoom.No matter what metering areas are, the final exposure are compensated by setExposureCompensation(int).
2. 坐标转换
根据前面对相机坐标的说明,对坐标进行转换就很简单了。
我采用的方法是:计算坐标到左上角的x、y方向的距离,与x、y轴长度的百分比,然后乘以新坐标的x、y轴长度,再根据原点与左上角的位置计算坐标。核心代码如下:
transX = (x / xMax) * 2000 - 1000
trnasY = (y / yMax) * 2000 - 1000
如果设置了预览画面的旋转角度(camera.setDisplayOrientation(orientation)
),由于触摸事件中MotionEvent对象传递的是屏幕坐标,所以需要旋转。为了方便,选择在相机坐标下旋转,代码如下:
Matrix matrix = new Matrix();
matrix.setRotate(orientation);
matrix.mapRect(rectF); // rectF是相机坐标下的矩形
完整的工具类代码如下:
package com.example.study.utils;import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;public class CameraAreaUtils {/*** 相机坐标区域是2000*2000,坐标原点在最中心*/private static final int CAMERA_COORDINATE_SIZE = 2000;/*** 原点到边界的距离*/private static final int CAMERA_COORDINATE_HALF_SIZE = CAMERA_COORDINATE_SIZE >> 1;/*** 根据中心点、边框边长、边框长度系数创建矩形区域** @param x x坐标* @param y y坐标* @param areaSide 边框边长* @param coefficient 边框长度系数* @param previewWidth 屏幕宽,也就是屏幕坐标轴的x轴* @param previewHeight 屏幕高,也就是屏幕坐标轴的y轴* @return 矩形*/public static Rect createRect(float x, float y, int areaSide, float coefficient,int previewWidth, int previewHeight) {int sideSize = (int) (areaSide * coefficient);int left = clamp(x - sideSize / 2, 0, previewWidth);int top = clamp(y - sideSize / 2, 0, previewHeight);int right = clamp(x + sideSize / 2, 0, previewWidth);int bottom = clamp(y + sideSize / 2, 0, previewHeight);if (right - left < sideSize) {if (left == 0) {right = Math.min(sideSize, previewWidth);}if (right == previewWidth) {left = Math.max(previewWidth - sideSize, 0);}}if (bottom - top < sideSize) {if (top == 0) {bottom = Math.min(sideSize, previewHeight);}if (bottom == previewHeight) {top = Math.max(previewHeight - sideSize, 0);}}return new Rect(left, top, right, bottom);}/*** 防止坐标越界** @param position 坐标* @param min 最小值* @param max 最大值* @return 坐标*/private static int clamp(float position, int min, int max) {int pos = Math.round(position);return pos < min ? min : pos > max ? max : pos;}/*** 屏幕矩形区域转为相机矩形区域** @param rect 屏幕矩形区域* @param orientation 预览画面的旋转角度* @param previewWidth 屏幕宽,也就是屏幕坐标轴的x轴* @param previewHeight 屏幕高,也就是屏幕坐标轴的y轴* @return 相机矩形区域*/public static Rect transToCamera(Rect rect, int orientation, int previewWidth, int previewHeight) {return rectFToRect(transToCamera(new RectF(rect), orientation, previewWidth,previewHeight));}/*** 屏幕矩形区域转为相机矩形区域** @param rectF 屏幕矩形区域* @param orientation 预览画面的旋转角度* @param previewWidth 屏幕宽,也就是屏幕坐标轴的x轴* @param previewHeight 屏幕高,也就是屏幕坐标轴的y轴* @return 相机矩形区域*/public static RectF transToCamera(RectF rectF, int orientation, int previewWidth, int previewHeight) {RectF cameraRectF = new RectF(transPositionToCameraCoordinate(rectF.left, previewWidth),transPositionToCameraCoordinate(rectF.top, previewHeight),transPositionToCameraCoordinate(rectF.right, previewWidth),transPositionToCameraCoordinate(rectF.bottom, previewHeight));// 预览画面如果有旋转,映射到相机坐标后,需要把旋转取消,才能对应真正的相机坐标Matrix matrix = new Matrix();matrix.setRotate(-1 * orientation);matrix.mapRect(cameraRectF);return cameraRectF;}/*** 将屏幕坐标转换为相机坐标** @param position 屏幕坐标某个方向的坐标值(如x)* @param srcSize 屏幕坐标对应方向的尺寸(如width)* @return 相机坐标下该方向的坐标值*/private static float transPositionToCameraCoordinate(float position, int srcSize) {return (position / srcSize) * CAMERA_COORDINATE_SIZE - CAMERA_COORDINATE_HALF_SIZE;}/*** 相机矩形区域转为屏幕矩形区域** @param rect 相机矩形区域* @param orientation 预览画面的旋转角度* @param previewWidth 屏幕宽,也就是屏幕坐标轴的x轴* @param previewHeight 屏幕高,也就是屏幕坐标轴的y轴* @return 屏幕矩形区域*/public static Rect transToScreen(Rect rect, int orientation, int previewWidth, int previewHeight) {return rectFToRect(transToScreen(new RectF(rect), orientation, previewWidth,previewHeight));}/*** 相机矩形区域转为屏幕矩形区域** @param rectF 相机矩形区域* @param orientation 预览画面的旋转角度* @param previewWidth 屏幕宽,也就是屏幕坐标轴的x轴* @param previewHeight 屏幕高,也就是屏幕坐标轴的y轴* @return 屏幕矩形区域*/public static RectF transToScreen(RectF rectF, int orientation, int previewWidth, int previewHeight) {// 先把相机坐标按预览的旋转角度进行旋转Matrix matrix = new Matrix();matrix.setRotate(orientation);matrix.mapRect(rectF);RectF screenRect = new RectF(transPositionToScreenCoordinate(rectF.left, previewWidth),transPositionToScreenCoordinate(rectF.top, previewHeight),transPositionToScreenCoordinate(rectF.right, previewWidth),transPositionToScreenCoordinate(rectF.bottom, previewHeight));return screenRect;}/*** 将相机坐标转换为屏幕坐标** @param position 相机坐标某个方向的坐标值(如x)* @param srcSize 相机坐标对应方向的尺寸(如width)* @return 屏幕坐标下该方向的坐标值*/private static float transPositionToScreenCoordinate(float position, int srcSize) {return ((position + CAMERA_COORDINATE_HALF_SIZE) / CAMERA_COORDINATE_SIZE) * srcSize;}/*** RectF转为Rect** @param rectF rectF对象* @return rect对象*/private static Rect rectFToRect(RectF rectF) {if (rectF == null) {return new Rect(0, 0, 0, 0);}Rect rect = new Rect();rect.left = (int) rectF.left;rect.top = (int) rectF.top;rect.right = (int) rectF.right;rect.bottom = (int) rectF.bottom;return rect;}
}
3. 应用于相机
布局文件activity_camera_demo.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><SurfaceViewandroid:id="@+id/camera_preview"android:layout_width="match_parent"android:layout_height="match_parent" /><com.example.study.views.DrawViewandroid:id="@+id/camera_preview_draw"android:layout_width="match_parent"android:layout_height="match_parent" />
</FrameLayout>
绘制对焦框的DrawView.java:
package com.example.study.views;import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;import androidx.annotation.Nullable;import java.util.ArrayList;
import java.util.List;public class DrawView extends View {private final Object lock = new Object();protected Paint paint;private final List<RectInfo> rects = new ArrayList<>();private final List<float[]> dots = new ArrayList<>();public DrawView(Context context) {super(context);}public DrawView(Context context, @Nullable AttributeSet attrs) {super(context, attrs);}public void clear() {synchronized (lock) {rects.clear();dots.clear();}postInvalidate();}public void add(Rect rect, int color) {synchronized (lock) {rects.add(new RectInfo(rect, color));}}public void add(float x, float y, int color) {synchronized (lock) {dots.add(new float[]{x, y, color});}}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);synchronized (lock) {paint = new Paint();paint.setStyle(Paint.Style.STROKE);for (RectInfo rectInfo : rects) {paint.setColor(rectInfo.color);paint.setStrokeWidth(4);canvas.drawRect(rectInfo.rect, paint);}for (float[] dot : dots) {paint.setColor((int) dot[2]);paint.setStrokeWidth(10);canvas.drawPoint(dot[0], dot[1], paint);}}}static class RectInfo {Rect rect;int color;public RectInfo(Rect rect, int color) {this.rect = rect;this.color = color;}}
}
触摸监听类TouchListener.java:
package com.example.study.listeners;import android.graphics.Color;
import android.graphics.Rect;
import android.hardware.Camera;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;import com.example.study.utils.CameraAreaUtils;
import com.example.study.views.DrawView;import java.util.ArrayList;
import java.util.List;public class TouchListener implements View.OnTouchListener {private static final String TAG = "TouchListener";private static final int AREA_SIDE = 210;private int orientation;private int leftMargin;private int topMargin;private Camera camera;private DrawView drawView;public TouchListener(Camera camera, int orientation, DrawView drawView, int leftMargin, int topMargin) {this.camera = camera;this.orientation = orientation;this.drawView = drawView;this.leftMargin = leftMargin;this.topMargin = topMargin;}@Overridepublic boolean onTouch(View view, MotionEvent event) {try {setAreas(event);} catch (Exception exception) {Log.i(TAG, exception.getMessage());}return true;}private void setAreas(MotionEvent event) {// 只有一根手指且按下时,才设置对焦区域if (event.getPointerCount() != 1 || event.getActionMasked() != MotionEvent.ACTION_DOWN) {return;}drawView.clear();// adjustSurface调整过左、上边距,所以需要加上边距float x = event.getX() + leftMargin;float y = event.getY() + topMargin;Camera.Parameters parameters = camera.getParameters();Camera.Size previewSize = parameters.getPreviewSize();boolean supportSetArea = false;// 检查是否支持设置对焦区域if (parameters.getMaxNumFocusAreas() > 0) {parameters.setFocusAreas(getAreas(x, y, 1.0f, previewSize));supportSetArea = true;}// 检查是否支持设置测光区域if (parameters.getMaxNumMeteringAreas() > 0) {parameters.setMeteringAreas(getAreas(x, y, 1.5f, previewSize));supportSetArea = true;}if (!supportSetArea) {return;}String currentFocusMode = parameters.getFocusMode();parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);camera.cancelAutoFocus();camera.setParameters(parameters);camera.autoFocus((success, camera) -> {drawRealArea(camera, x, y);Camera.Parameters params = camera.getParameters();params.setFocusMode(currentFocusMode);camera.setParameters(params);});}private void drawRealArea(Camera camera, float rawX, float y) {int height = camera.getParameters().getPreviewSize().height;int width = camera.getParameters().getPreviewSize().width;List<Camera.Area> focusAreas = camera.getParameters().getFocusAreas();if (focusAreas != null) {for (Camera.Area focusArea : focusAreas) {// previewSize的width和height正好相反Rect rect = CameraAreaUtils.transToScreen(focusArea.rect, orientation, height, width);// 绘制对焦区域draw(rect, rawX, y, Color.GREEN);}}}private List<Camera.Area> getAreas(float rawX, float y, float coefficient, Camera.Size previewSize) {// previewSize的width和height正好相反Rect area = CameraAreaUtils.createRect(rawX, y, AREA_SIDE, coefficient, previewSize.height, previewSize.width);List<Camera.Area> areas = new ArrayList<>();// weight:权重,取值范围为1-1000areas.add(new Camera.Area(CameraAreaUtils.transToCamera(area, orientation, previewSize.height,previewSize.width), 800));// 绘制对焦/测光区域draw(area, rawX, y, coefficient > 1.1f ? Color.YELLOW : Color.WHITE);return areas;}private void draw(Rect rect, float x, float y, int color) {drawView.add(rect, color);drawView.add(x, y, color);drawView.setBackgroundColor(Color.TRANSPARENT);drawView.invalidate();}
}
activity类:
package com.example.study.activities;import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.FrameLayout;import androidx.activity.ComponentActivity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;import com.example.study.R;
import com.example.study.listeners.TouchListener;
import com.example.study.views.DrawView;public class CameraDemoActivity extends ComponentActivity implements Camera.PreviewCallback, SurfaceHolder.Callback {private static final String TAG = "CameraDemoActivity";private static final int REQUEST_CAMERA = 1000;private static final int WIDTH = 1920;private static final int HEIGHT = 1080;private static final int ORIENTATION = 90;private int leftMargin = 0;private int topMargin = 0;private SurfaceView preview;private DrawView drawView;private Camera camera;private Camera.Parameters parameters;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.setContentView(R.layout.activity_camera_demo);preview = findViewById(R.id.camera_preview);drawView = findViewById(R.id.camera_preview_draw);adjustSurface(preview);// 检查权限if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);} else {preview.getHolder().addCallback(this);}}private void adjustSurface(SurfaceView cameraPreview) {FrameLayout.LayoutParams paramSurface = (FrameLayout.LayoutParams) cameraPreview.getLayoutParams();if (getSystemService(Context.WINDOW_SERVICE) != null) {WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);Display defaultDisplay = windowManager.getDefaultDisplay();Point outPoint = new Point();defaultDisplay.getRealSize(outPoint);float sceenWidth = outPoint.x;float sceenHeight = outPoint.y;float rate;if (sceenWidth / (float) HEIGHT > sceenHeight / (float) WIDTH) {rate = sceenWidth / (float) HEIGHT;int targetHeight = (int) (WIDTH * rate);paramSurface.width = FrameLayout.LayoutParams.MATCH_PARENT;paramSurface.height = targetHeight;topMargin = (int) (-(targetHeight - sceenHeight) / 2);if (topMargin < 0) {paramSurface.topMargin = topMargin;}} else {rate = sceenHeight / (float) WIDTH;int targetWidth = (int) (HEIGHT * rate);paramSurface.width = targetWidth;paramSurface.height = FrameLayout.LayoutParams.MATCH_PARENT;leftMargin = (int) (-(targetWidth - sceenWidth) / 2);if (leftMargin < 0) {paramSurface.leftMargin = leftMargin;}}}}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);if (requestCode == REQUEST_CAMERA && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {preview.getHolder().addCallback(this);surfaceCreated(preview.getHolder());camera.setPreviewCallback(this);camera.startPreview();}}@Overridepublic void onPreviewFrame(byte[] data, Camera camera) {Log.i(TAG, "接收到一帧图片");}@Overridepublic void surfaceCreated(@NonNull SurfaceHolder holder) {try {camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);parameters = camera.getParameters();parameters.setPictureSize(WIDTH, HEIGHT);parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);parameters.setPictureFormat(ImageFormat.NV21);camera.setPreviewDisplay(holder);camera.setDisplayOrientation(ORIENTATION);camera.setParameters(parameters);preview.setOnTouchListener(new TouchListener(camera, ORIENTATION, drawView, leftMargin, topMargin));} catch (Exception exception) {Log.i(TAG, exception.getMessage());}}@Overridepublic void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {if (camera != null) {camera.stopPreview();camera.setPreviewCallback(null);camera.startPreview();camera.setPreviewCallback(this);}}@Overridepublic void surfaceDestroyed(@NonNull SurfaceHolder holder) {if (camera != null) {camera.stopPreview();camera.setPreviewCallback(null);camera.release();}}
}