iOS中为view添加圆角效果有两种方式,一种基于“离屏渲染”(off-screen-renderring),直接设置view的layer层参数即可简单实现,也很常用,但性能较低;另一种则是编写底层图形代码,实现‘在屏渲染’(on-screen-renderring),可以大大优化绘制性能。
iOS中圆角效果实现的最简单、最直接的方式,是直接修改View的layer层参数:
view.layer.cornerRadius = 5
view.layer.masksToBounds = YES
这种方法最简单快速,但其实这种方法的实现是靠的‘离屏渲染’(off-screen-rendering),性能很低。
另外一种则是实现on-screen-rendering,用于提高性能。
为UIImage类扩展一个实例函数:
/**
* On-screen-renderring绘制UIImage矩形圆角
*/
- (UIImage *)imageWithCornerRadius:(CGFloat)radius ofSize:(CGSize)size{
CGRect rect = (CGRect){0.f,0.f,size};
UIGraphicsBeginImageContextWithOptions(size, NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
使用时,让实例化的UIImage对象调用一下上面的实例方法即可:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
UIImage *image = [UIImage imageNamed:@"icon"];
image = [image imageWithCornerRadius:50 ofSize:imageView.frame.size];
[imageView setImage:image];
完整代码
![这里写图片描述](https://img-blog.csdn.net/20170419152100294?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY29yZG92YQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
UIImage类别扩展在屏渲染实例函数:
#import <UIKit/UIKit.h>
@interface UIImage (RadiusCorner)
- (UIImage *)imageWithCornerRadius:(CGFloat)radius ofSize:(CGSize)size;
@end
#import "UIImage+RadiusCorner.h"
@implementation UIImage (RadiusCorner)
/**
* On-screen-renderring绘制UIImage矩形圆角
*/
- (UIImage *)imageWithCornerRadius:(CGFloat)radius ofSize:(CGSize)size{
CGRect rect = (CGRect){0.f,0.f,size};
UIGraphicsBeginImageContextWithOptions(size, NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
测试代码:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
UIImage *image = [UIImage imageNamed:@"icon"];
[imageView setImage:image];
imageView.layer.cornerRadius = 20;
imageView.layer.masksToBounds = YES;
[self.view addSubview:imageView];
}
@end