简体   繁体   English

设置UIView的cornerRadius时如何防止裁剪子视图?

[英]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.

相关问题 Parent UIView不包含/剪辑子视图 - Parent UIView not containing/clipping subviews 旋转UIView; 如何防止旋转过程中发生削波? - Rotating a UIView; How to prevent clipping during rotation? 如何设置 UIStackView 的cornerRadius? - How can I set the cornerRadius of a UIStackView? Xamarin.iOS:如何在外部单击时隐藏带有子视图的UIView,而不在单击子视图时隐藏它? - Xamarin.iOS: How do I hide a UIView with subviews when clicked outside it without hiding it when clicked on the subviews? 如何防止键盘遮盖UIViewController上的子视图? - How can I prevent the keyboard from covering up subviews on a UIViewController? 如何防止UITabBarController更新子视图? - How do I prevent UITabBarController from updating subviews? 设置 UIView 大小以适合子视图 - Set UIView size to fit subViews 当我在旋转uiview中触摸图像时如何检测图像子视图的标签 - how to detect the tag ofimage subviews when i touched the image in the rotatory uiview 如何防止UIButton“ clipsToBounds”剪切标签? - How to prevent UIButton “clipsToBounds” from clipping label? 如何将UIView高度设置为等于两个子视图UILabel的最大值? - How to set UIView height equal to max of two subviews UILabel?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM