0

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!

trey.lin
  • 15
  • 1
  • 4

2 Answers2

1

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
Christian Schnorr
  • 10,768
  • 8
  • 48
  • 83
  • Thanks! But in this case, this avatar view is a subclass of UIButton, the avatar is set by some URL using some complex logic, so if I need to refactor it, it will have a lot of work to do... – trey.lin Jun 25 '15 at 16:01
0

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;
Pankaj Wadhwa
  • 3,073
  • 3
  • 28
  • 37