如何为相机视图添加中间带方形孔的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
相关产品推荐
相关产品推荐

