Flutter 将圆形遮罩到容器中 [英] Flutter mask a circle into a container
问题描述
我想在容器上添加圆形效果,但我希望圆形不会扩展容器的尺寸,而是被它剪裁.这就是我想要实现的目标:
I want to add a circle effect over a container, but I want the circle to not extend the dimensions of the container, but instead get clipped by it. This is what I'm trying to achieve:
正如您所看到的,白色圆圈自然会延伸红色容器,但相反,我试图让它留在边界内.我该怎么做?
As you can see the white circle naturally would extend the red container but instead, I'm trying to make it stay into the borders. How can I do it?
推荐答案
最简单的方法是使用重叠和剪辑矩形.
The simplest way to do this is to using an overlap and cliprect.
class OverlapSquare extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.red,
),
child: ClipRect(
clipBehavior: Clip.hardEdge,
child: OverflowBox(
maxHeight: 250,
maxWidth: 250,
child: Center(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
),
),
),
),
);
}
}
OverFlowBox 允许圆在其父级边界之外绘制,然后 cliprect 将其切回边缘.
The OverFlowBox allows the circle to draw outside the bounds of its parent, and then the cliprect cuts it back to the edge.
仅供参考 - 在我的设备上,我在顶部看到一条细小的红线 &白色圆圈的底部.我很确定这是最近在颤振中引入的错误,因为如果我在容器周围放置白色边框,我也会看到类似的东西.为此,我在 github 上提出了 一个问题.
Just an FYI - on my device I'm getting a tiny red line at the top & bottom of the white circle. I'm fairly sure that's a recently-introduced bug in flutter as I'm also seeing something similar if I put a white border around the container. I've raised an issue on github for that.
这篇关于Flutter 将圆形遮罩到容器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!