10

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: enter image description here

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?

Fabrizio
  • 1,138
  • 4
  • 18
  • 41

2 Answers2

19

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,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

The OverFlowBox allows the circle to draw outside the bounds of its parent, and then the cliprect cuts it back to the edge.

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.

rmtmckenzie
  • 37,718
  • 9
  • 112
  • 99
  • that worked! Thank you!!, but just as a sidenote. If I do not have the size to put into the maxHeight and maxWidth but I wanted to costraint them to the size of the parent, how could I do? – Fabrizio Dec 06 '18 at 15:41
  • Sorry - I don't quite understand. If you want it to be the size of the parent, you don't need the clipping do you? That being said, look at [LayoutBuilder](https://docs.flutter.io/flutter/widgets/LayoutBuilder-class.html) as it might be what you're looking for. – rmtmckenzie Dec 06 '18 at 16:37
  • If I need the white container to be centered on the left how could I do? – Fabrizio Apr 14 '19 at 21:33
  • Instead of using Center, you should be able to use Align with the appropriate alignment set. – rmtmckenzie Apr 15 '19 at 17:47
7

ClipRRect worked best for me.

See reference video: https://www.youtube.com/watch?v=eI43jkQkrvs&vl=en

ClipRRect(
  borderRadius: BorderRadius.cirular(10),
  child: myContainerWithCircleWidget,
);
Travis M.
  • 10,930
  • 1
  • 56
  • 72