[英]How to prevent from clipping the subviews when I set the cornerRadius of a UIView?
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. 我正在尝试设置UIButton的子类视图的cornerRadius,圆角以正确的方式显示,但是当我尝试在其上添加subView(花形图标)时,该子视图似乎像在图片上一样被剪切了。在下面的右侧 ,这不是我所期望的。 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;
Hope someone can help me to understand how to prevent from clipping. 希望有人可以帮助我了解如何防止裁剪。
Thanks! 谢谢!
You shouldn't add the overlay as a subview then. 然后,您不应该将叠加层添加为子视图。 Subviews will be clipped if you set clipsToBounds
to YES
. 如果将clipsToBounds
设置为YES
则子视图将被裁剪。
Instead add it as a sibling, like so: 而是将其添加为同级,如下所示:
- container view
- image view (clips)
- overlay view
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: 如果您使用上述代码对按钮进行四舍五入,那么您的按钮肯定会从角落切掉,因此,如果您只想从3个角落切掉,请执行以下操作:
#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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.