How to prevent from clipping the subviews when I set the cornerRadius of a UIView?

3.2k views Asked by At

I am trying to set the cornerRadius of a subclass view of UIButton, the round corner shows in a right way, but when I try to add a subView(the flower icon) on it, the subview seems to be clipped like the picture on the right side below, this is not what I expected. I try to make the correct appearance like the picture shows on the left side, the icon not be clipped. The code I use:

button.layer.cornerRadius = button.frame.width / 2;
button.layer.masksToBounds = Yes;    

Avatar View(left) Avatar View(right)

Hope someone can help me to understand how to prevent from clipping.
Thanks!

2

There are 2 answers

3
Pankaj Wadhwa On

If you are making the button rounded using your above mentioned code then your button will definitely get chopped from the corners so if you only want to chop it from 3 corners then do this:

#import <QuartzCore/CoreAnimation.h>

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:button.bounds 
                                           byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft
                                                 cornerRadii:CGSizeMake(7.0, 7.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = button.bounds;
maskLayer.path = maskPath.CGPath;
button.layer.mask = maskLayer;
1
Christian Schnorr On

You shouldn't add the overlay as a subview then. Subviews will be clipped if you set clipsToBounds to YES.

Instead add it as a sibling, like so:

- container view
  - image view (clips)
  - overlay view