iOS 正确设置圆角

参考文章
  • https://www.jianshu.com/p/e879aeff93f3
  • https://bestswifter.com/efficient-rounded-corner/
如果圆角不是很多的情况下可以直接用以下代码切圆角
view.layer.cornerRadius = 30.0f;
view.layer.masksToBounds = YES;

*cornerRadius 是可以直接切圆角的,但是如果此视图有子视图的话必须要加上 masksToBounds ,但是 masksToBounds就会引起性能损耗和离屏渲染

UIView 圆角的做法
-(void)setRounderCornerWithRadius:(CGFloat)radius withSize:(CGSize)size withBackGroundColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextRef ref = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(ref, color.CGColor);
    CGContextSetStrokeColorWithColor(ref, [UIColor redColor].CGColor);
    
    CGContextMoveToPoint(ref, size.width, size.height-radius);
    CGContextAddArcToPoint(ref, size.width, size.height, size.width-radius, size.height, radius);//右下角
    CGContextAddArcToPoint(ref, 0, size.height, 0, size.height-radius, radius);//左下角
    CGContextAddArcToPoint(ref, 0, 0, radius, 0, radius);//左上角
    CGContextAddArcToPoint(ref, size.width, 0, size.width, radius, radius);//右上角
    CGContextClosePath(ref);
    CGContextDrawPath(ref, kCGPathFillStroke);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    [imageView setImage:image];
    [self insertSubview:imageView atIndex:0];
}
UIImage 圆角的做法
-(UIImage *)setImageRoundedWithRadius:(CGFloat)radius withSize:(CGSize)size
{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef ref = UIGraphicsGetCurrentContext();
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
    CGContextAddPath(ref, path.CGPath);
    CGContextClip(ref);
    [self drawInRect:rect];
    CGContextDrawPath(ref, kCGPathFillStroke);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

你可能感兴趣的:(iOS 正确设置圆角)