You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何将方形相机遮罩转为圆形以拍摄自拍?

实现flutter_camera_overlay圆形自拍遮罩

要实现圆形遮罩来拍摄自拍,你可以通过自定义遮罩组件结合flutter_camera_overlay的customOverlay参数来完成,具体步骤如下:

1. 自定义圆形遮罩Widget

创建一个自定义Widget,实现中间镂空圆形的遮罩效果。核心思路是用CustomPaint绘制半透明背景+圆形镂空区域:

class CircleCameraOverlay extends StatelessWidget {
  final double radius;
  final Color backgroundColor;
  final Color circleBorderColor;

  const CircleCameraOverlay({
    super.key,
    this.radius = 150,
    this.backgroundColor = const Color.fromRGBO(0, 0, 0, 0.7),
    this.circleBorderColor = Colors.white,
  });

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: MediaQuery.of(context).size,
      painter: _CircleOverlayPainter(
        radius: radius,
        backgroundColor: backgroundColor,
        circleBorderColor: circleBorderColor,
      ),
    );
  }
}

class _CircleOverlayPainter extends CustomPainter {
  final double radius;
  final Color backgroundColor;
  final Color circleBorderColor;

  _CircleOverlayPainter({
    required this.radius,
    required this.backgroundColor,
    required this.circleBorderColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // 绘制半透明背景层
    final backgroundPaint = Paint()..color = backgroundColor;
    canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), backgroundPaint);

    // 绘制圆形边框
    final borderPaint = Paint()
      ..color = circleBorderColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3;
    final center = Offset(size.width / 2, size.height / 2);
    canvas.drawCircle(center, radius, borderPaint);

    // 挖空圆形区域(使用混合模式清除)
    final clearPaint = Paint()..blendMode = BlendMode.clear;
    canvas.drawCircle(center, radius, clearPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

2. 集成到flutter_camera_overlay中

在使用CameraOverlay组件时,关闭默认矩形遮罩,将customOverlay参数传入我们自定义的圆形遮罩:

CameraOverlay(
  camera: frontCameraDescription, // 传入前置相机描述
  overlay: const OverlayFormat(
    format: OverlayFormat.none, // 禁用默认遮罩样式
  ),
  customOverlay: CircleCameraOverlay(radius: 160), // 自定义圆形遮罩
  previewBarrierColor: Colors.transparent, // 避免遮挡自定义遮罩
  onCapture: (File imageFile) {
    // 处理拍摄完成后的照片
  },
  onSwitchCamera: () {
    // 切换相机逻辑
  },
)

额外优化建议

  • 动态适配不同屏幕:可以根据屏幕宽度比例计算半径,比如radius: MediaQuery.of(context).size.width * 0.4
  • 添加提示文本:在CircleCameraOverlay里嵌套Stack,在圆形下方添加"将面部置于圆形内"的提示文字
  • 增强交互:可以在圆形中心添加小型对焦图标,提升用户引导性

内容的提问来源于stack exchange,提问作者wolfsoft Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:52:11