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

如何为相机视图添加中间带方形孔的0.5透明度黑色遮罩?求简便方案

实现相机视图半透明遮罩(中间留方形孔洞)的简便方案

不需要用CustomPainter,用Flutter基础Widget就能轻松实现,推荐两种简便方法:

方法1:用Stack+行列组合实现(最易理解)

通过拆分遮罩为顶部、底部、左侧、右侧四个区域,中间自然留出方形孔洞,完全不用自定义绘制:

Stack(
  fit: StackFit.expand,
  children: [
    // 替换成你的相机视图Widget
    Container(color: Colors.blue),
    
    LayoutBuilder(
      builder: (context, constraints) {
        // 中间方形的尺寸,可按需调整
        final squareSize = 200.0;
        // 自动计算居中位置
        final topOffset = (constraints.maxHeight - squareSize) / 2;
        final leftOffset = (constraints.maxWidth - squareSize) / 2;

        return Column(
          children: [
            // 顶部遮罩
            Expanded(child: Container(color: Colors.black.withOpacity(0.5))),
            
            Row(
              children: [
                // 左侧遮罩
                Expanded(child: Container(color: Colors.black.withOpacity(0.5))),
                // 中间方形孔洞(留空)
                SizedBox(width: squareSize, height: squareSize),
                // 右侧遮罩
                Expanded(child: Container(color: Colors.black.withOpacity(0.5))),
              ],
            ),
            
            // 底部遮罩
            Expanded(child: Container(color: Colors.black.withOpacity(0.5))),
          ],
        );
      },
    ),
  ],
)

这种方式的优势是逻辑直观,调整尺寸只需要改squareSize,适配各种屏幕,且没有自定义绘制的复杂度。

方法2:用Stack+BlendMode实现挖洞效果

通过混合模式直接在遮罩层上"挖"出孔洞,代码更简洁:

import 'package:flutter/rendering.dart';

// ...

Stack(
  fit: StackFit.expand,
  children: [
    // 相机视图
    Container(color: Colors.blue),
    
    // 半透明黑色遮罩
    Container(color: Colors.black.withOpacity(0.5)),
    
    // 中间的方形孔洞
    Positioned.fill(
      child: Center(
        child: SizedBox(
          width: 200,
          height: 200,
          child: BlendModeMask(
            blendMode: BlendMode.dstOut,
            child: Container(color: Colors.black),
          ),
        ),
      ),
    ),
  ],
)

需要注意:BlendModeMask属于Flutter渲染层,需要导入flutter/rendering.dart;部分平台(比如Web)对混合模式的支持可能有差异,测试时需要留意。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:15:36