用系统方法设置圆角:
view.layer.cornerRadius = 10.0f;
[view setMasksToBounds:YES];
这样设置一般情况来说是没有问题的,但是对于在UITableview,UICollectionView,中的子视图这样设置会影响性能,所以我想了一种思路去实现圆角效果又不影响性能,大家一起讨论一下。
思路: 写一个UIView的分类,在分类的load方法中通过runtime替换系统的layoutSublayersOfLayer方法,再通过赛贝尔曲线结合CAShapeLayer绘制出想要的圆角
在.h文件中
typedef NS_ENUM(NSInteger, YJBCornerPosition) {
YJBCornerPositionTop,
YJBCornerPositionLeft,
YJBCornerPositionBottom,
YJBCornerPositionRight,
YJBCornerPositionAll
};
@interface UIView (Corner)
@property (nonatomic, assign) YJBCornerPosition yjb_cornerPosition;
@property (nonatomic, assign) CGFloat yjb_cornerRadius;
- (void)yjb_setAllCornerWithRadius:(CGFloat)radius;
@end
在.m文件中
static NSString * const CornerPositionKey = @"CornerPositionKey";
static NSString * const CornerRadiusKey = @"CornerRadiusKey";
@implementation UIView (Corner)
+ (void)load
{
SEL ori = @selector(layoutSublayersOfLayer:);
SEL new = NSSelectorFromString([@"p_" stringByAppendingString:NSStringFromSelector(ori)]);
p_swizzle(self, ori, new);
}
void p_swizzle(Class c, SEL orig, SEL new)
{
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
method_exchangeImplementations(origMethod, newMethod);
}
//yjb_cornerRadius 是要设置的圆角半径
- (void)p_layoutSublayersOfLayer:(CALayer *)layer
{
[self p_layoutSublayersOfLayer:layer];
if (self.yjb_cornerRadius>0)
{
[self setRadius:self.yjb_cornerRadius WithCorners:self.yjb_cornerPosition];
}
}
//这个是核心的代码
- (void)setRadius:(CGFloat)radius WithCorners:(YJBCornerPosition)position
{
UIRectCorner corners = 0;
switch (position) {
case YJBCornerPositionTop:
corners = (UIRectCornerTopLeft| UIRectCornerTopRight);
break;
case YJBCornerPositionLeft:
corners = (UIRectCornerTopLeft| UIRectCornerBottomRight);
break;
case YJBCornerPositionBottom:
corners = (UIRectCornerBottomLeft| UIRectCornerBottomRight);
break;
case YJBCornerPositionRight:
corners = (UIRectCornerTopRight | UIRectCornerBottomRight);
break;
case YJBCornerPositionAll:
corners = UIRectCornerAllCorners;
break;
default:
break;
}
CGRect rect = CGRectMake(0, 0, self.bounds.size.width,self.bounds.size.height);
//绘制赛贝尔曲线
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
//图层渲染
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = rect;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
self.layer.shouldRasterize = YES;
self.layer.rasterizationScale = [UIScreen mainScreen].scale;
}