Android人脸识别绘制人脸框自定义View显示

该文章展示了如何在Android中创建一个自定义的FaceBoundsView,该视图在onDraw方法中重绘矩形以表示人脸检测框。通过设置FaceBounds,可以在Canvas上绘制绿色边框的矩形。此组件可用于移动应用中显示面部识别的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建一个自定义的View,它将绘制人脸框,并重写 onDraw 方法以绘制矩形。 下面是一个示例代码:

public class FaceBoundsView extends View {

    private List<Rect> faceBounds;
    private Paint rectPaint;

    public FaceBoundsView(Context context) {
        super(context);
        init();
    }

    public FaceBoundsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public FaceBoundsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        rectPaint = new Paint();
        rectPaint.setColor(Color.GREEN);
        rectPaint.setStyle(Paint.Style.STROKE);
        rectPaint.setStrokeWidth(5);
    }

    public void setFaceBounds(List<Rect> faceBounds) {
        this.faceBounds = faceBounds;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (faceBounds != null) {
            for (Rect rect : faceBounds) {
                canvas.drawRect(rect, rectPaint);
            }
        }
    }
}

在Activity或Fragment中,您可以按如下方式使用此视图:

FaceBoundsView faceBoundsView = findViewById(R.id.face_bounds_view);
faceBoundsView.setFaceBounds(faceBounds);

在布局中,您可以按如下方式添加此视图

<com.example.FaceBoundsView
    android:id="@+id/face_bounds_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值