在开启人脸检测之前,需要在相机 AutoFitTextureView 上覆盖一层自定义 BoundingBoxView 用于绘制检测到的人脸矩形框,该 View 的具体实现如下:
public class BoundingBoxView extends SurfaceView implements SurfaceHolder.Callback { protected SurfaceHolder mSurfaceHolder; private Paint mPaint; private boolean mIsCreated; public BoundingBoxView(Context context, AttributeSet attrs) { super(context, attrs); mSurfaceHolder = getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT); setZOrderOnTop(true); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(Color.RED); mPaint.setStrokeWidth(5f); mPaint.setStyle(Paint.Style.STROKE); } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { mIsCreated = true; } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { mIsCreated = false; } public void setResults(List<VisionDetRet> detRets) { if (!mIsCreated) { return; } Canvas canvas = mSurfaceHolder.lockCanvas(); //清除掉上一次的画框。 canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); canvas.drawColor(Color.TRANSPARENT); for (VisionDetRet detRet : detRets) { Rect rect = new Rect(detRet.getLeft(), detRet.getTop(), detRet.getRight(), detRet.getBottom()); canvas.drawRect(rect, mPaint); } mSurfaceHolder.unlockCanvasAndPost(canvas); } }同时,需要在布局文件中添加对应的 BoundingBoxView 层,保证与 AutoFitTextureView 完全重合:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".CameraFragment"> <com.lightweh.facedetection.AutoFitTextureView android:id="@+id/textureView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> <com.lightweh.facedetection.BoundingBoxView android:id="@+id/boundingBoxView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textureView" android:layout_alignTop="@+id/textureView" android:layout_alignRight="@+id/textureView" android:layout_alignBottom="@+id/textureView" /> </RelativeLayout>BoundingBoxView 添加完成以后,即可在 CameraFragment 中添加对应的人脸检测代码:
private class detectAsync extends AsyncTask<Bitmap, Void, List<VisionDetRet>> { @Override protected void onPreExecute() { mIsDetecting = true; super.onPreExecute(); } protected List<VisionDetRet> doInBackground(Bitmap... bp) { List<VisionDetRet> results; // 返回检测结果 results = mFaceDet.detect(bp[0]); return results; } protected void onPostExecute(List<VisionDetRet> results) { // 绘制检测到的人脸矩形框 mBoundingBoxView.setResults(results); mIsDetecting = false; } }