一般情况下我们给UIKit控件添加圆角都是改变clipsToBounds和layer.cornerRadius,这样虽然看似简单,两行代码就可以搞定。但是,这样使用会强制Core Animation提前渲染屏幕的离屏绘制,而离屏绘制就会为性能带来负面影响。
下面为大家提供一种比较复杂的方式来为控件添加圆角:
#import <UIKit/UIKit.h>
@interface UIView (RoundedCorner)
// 设置顶部圆角
- (void)setRoundedCornerOnTop;
// 设置底部圆角
- (void)setRoundedCornerOnBottom;
// 设置圆角
- (void)setRoundedCorner;
// 取消圆角
- (void)removeRoundedCorner;
// 自定义圆角大小 scale范围:0 ~ 0.5
- (void)setRoundedCornerWithScale:(CGFloat)scale;
// 自定义顶部圆角大小 scale范围:0 ~ 0.5
- (void)setRoundedCornerOnTopWithScale:(CGFloat)scale;
// 自定义底部圆角大小 scale范围:0 ~ 0.5
- (void)setRoundedCornerOnBottomWithScale:(CGFloat)scale;
@end
#import "UIView+RoundedCorner.h"
@implementation UIView (RoundedCorner)
- (void)setRoundedCornerOnTop {
[self setRoundedCornerOnTopWithScale:0.5];
}
- (void)setRoundedCornerOnBottom {
[self setRoundedCornerOnBottomWithScale:0.5];
}
- (void)setRoundedCorner {
[self setRoundedCornerWithScale:0.5];
}
- (void)removeRoundedCorner {
self.layer.mask = nil;
}
- (void)setRoundedCornerWithScale:(CGFloat)scale {
if (scale > 0.5) {
scale = 0.5;
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.frame.size.height * scale];
[self setShapeLayer:maskPath];
}
- (void)setRoundedCornerOnTopWithScale:(CGFloat)scale {
if (scale > 0.5) {
scale = 0.5;
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(self.frame.size.height * scale, self.frame.size.height * scale)];
[self setShapeLayer:maskPath];
}
- (void)setRoundedCornerOnBottomWithScale:(CGFloat)scale {
if (scale > 0.5) {
scale = 0.5;
}
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(self.frame.size.height * scale, self.frame.size.height * scale)];
[self setShapeLayer:maskPath];
}
// 创建CAShapeLayer并设置
- (void)setShapeLayer:(UIBezierPath *)maskPath {
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
@end
当然还有给UIImageView添加圆角的方法。(注意:如果加载的是网络图片,必须要等网络图片加载完成再调用)
#import <UIKit/UIKit.h>
@interface UIImageView (RoundedCorner)
- (UIImageView *)imageViewWithRoundedCornerSize:(CGFloat)cornerRadius;
@end
#import "UIImageView+RoundedCorner.h"
@implementation UIImageView (RoundedCorner)
- (UIImageView *)imageViewWithRoundedCornerSize:(CGFloat)cornerRadius {
UIImageView *imageView = self;
UIImage *original = self.image;
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:cornerRadius] addClip];
[original drawInRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageView;
}
@end