如何在JourneyApps ZXing二维码扫描器的Canvas中绘制圆角边界
解决ZXing扫描框圆角边界绘制问题
要实现带圆角的扫描框边角线条,不能再用drawRect绘制直角矩形,改用Path构建带圆弧的路径来绘制即可。以下是修改后的完整代码:
// 线条与扫描框的长度比例 private float mLineRate = 0.1f; // 线条厚度 private float mLineDepth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()); // 线条颜色 private int mLineColor = Color.rgb(244, 165, 37); // 圆角半径(可根据需求调整DIP值) private float mCornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()); @Override public void onDraw (Canvas canvas){ refreshSizes(); if (framingRect == null || previewSize == null) { return; } final Rect frame = framingRect; final Size previewSize = this.previewSize; final int width = getWidth(); final int height = getHeight(); // [Custom start] 绘制带圆角的4个边角线条 paint.setColor(mLineColor); paint.setStyle(Paint.Style.STROKE); // 设置为线条模式 paint.setStrokeWidth(mLineDepth); paint.setAntiAlias(true); // 抗锯齿优化圆角边缘 Path path = new Path(); float lineLengthHorizontal = frame.width() * mLineRate; float lineLengthVertical = frame.height() * mLineRate; // 左上角 path.moveTo(frame.left + mCornerRadius, frame.top); path.lineTo(frame.left + lineLengthHorizontal, frame.top); path.moveTo(frame.left, frame.top + mCornerRadius); path.lineTo(frame.left, frame.top + lineLengthVertical); path.addArc(frame.left, frame.top, frame.left + 2 * mCornerRadius, frame.top + 2 * mCornerRadius, 180, 90); // 右上角 path.moveTo(frame.right - mCornerRadius, frame.top); path.lineTo(frame.right - lineLengthHorizontal, frame.top); path.moveTo(frame.right, frame.top + mCornerRadius); path.lineTo(frame.right, frame.top + lineLengthVertical); path.addArc(frame.right - 2 * mCornerRadius, frame.top, frame.right, frame.top + 2 * mCornerRadius, 270, 90); // 左下角 path.moveTo(frame.left + mCornerRadius, frame.bottom); path.lineTo(frame.left + lineLengthHorizontal, frame.bottom); path.moveTo(frame.left, frame.bottom - mCornerRadius); path.lineTo(frame.left, frame.bottom - lineLengthVertical); path.addArc(frame.left, frame.bottom - 2 * mCornerRadius, frame.left + 2 * mCornerRadius, frame.bottom, 90, 90); // 右下角 path.moveTo(frame.right - mCornerRadius, frame.bottom); path.lineTo(frame.right - lineLengthHorizontal, frame.bottom); path.moveTo(frame.right, frame.bottom - mCornerRadius); path.lineTo(frame.right, frame.bottom - lineLengthVertical); path.addArc(frame.right - 2 * mCornerRadius, frame.bottom - 2 * mCornerRadius, frame.right, frame.bottom, 0, 90); canvas.drawPath(path, paint); // [Custom end] }
关键修改说明
- 新增
mCornerRadius变量控制圆角大小,单位转换为DP保证多设备一致性 - 将画笔模式改为
STROKE,确保绘制的是线条而非填充区域 - 用
Path分别构建每个角的短线条+圆弧路径:- 短线条的起点/终点避开圆角区域,避免与圆弧重叠
- 通过
addArc添加对应角度的圆弧,圆弧的矩形范围是角点向外扩展2倍圆角半径的区域
- 开启抗锯齿让圆角边缘更平滑自然
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

