谈iOS实现圆角

一.正常圆角的实现

在做项目过程中,我们总会遇到实现圆角的情况

1.通过layer来实现

- (UIImageView *)testImageView
{
    if (_testImageView) {
        _testImageView = [[UIImageView alloc] init];
        _testImageView.layer.cornerRadius = 5.0; // 圆角
        _testImageView.layer.masksToBounds = YES; // 切掉多余的地方
    }
    return _testImageView;
}

2.通过GPU来做

//
//  UIImage+GetCornerRadius.m
//  GetCornerRadius
//
//  Created by Cyrill on 16/8/18.
//  Copyright © 2016年 Cyrill. All rights reserved.
//

#import "UIImage+GetCornerRadius.h"

@implementation UIImage (GetCornerRadius)

//圆角切割
- (UIImage *)cy_getCornerRadius:(CGFloat)cornerRadius
{
    CGFloat scale = [UIScreen mainScreen].scale;
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, scale);
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
    CGContextAddPath(c, path.CGPath);
    CGContextClip(c);
    
    [self drawInRect:rect];
    
    CGContextDrawPath(c, kCGPathFillStroke);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

@end

这样会返回一个已经切割好的图片。好处是用GPU来处理圆角效果,一些情况下会提升app的性能。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容