07头像切圆角的三种方式
2017-03-01 本文已影响34人
i爱吃土豆的猫
图片资源经常用, 所以要放到 UIImage Assets xcassest
切圆角图片.png第一种方法:通过设置层的属性
最简单的一种,但是很影响性能,一般在正常的开发中使用很少。
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
//只需要设置layer层的两个属性
//设置圆角
imageView.layer.cornerRadius = imageView.frame.size.width / 2;
//将多余的部分切掉
imageView.layer.masksToBounds = YES;
[self.view addSubview:imageView];
第二种方法:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"1"];
//开始对imageView进行画图
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);
//使用贝塞尔曲线画出一个圆形图
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
[imageView drawRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
//结束画图
UIGraphicsEndImageContext();
[self.view addSubview:imageView];
第三种方法:使用UIBezierPath和CAShapeLayer设置圆角
这三种方法中第三种最好,对内存的消耗最少啊,而且渲染快速。
首先需要导入<AVFoundation/AVFoundation.h>
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"1"];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
//设置大小
maskLayer.frame = imageView.bounds;
//设置图形样子
maskLayer.path = maskPath.CGPath;
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];
}
建立起的分类
UIImage+Extension.h
#import <UIKit/UIKit.h>
@interface UIImage (Extension)
/// 根据当前图像,和指定的尺寸,生成圆角图像并且返回
- (void)cz_cornerImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor completion:(void (^)(UIImage *image))completion;
@end
UIImage+Extension.m
#import "UIImage+Extension.h"
@implementation UIImage (Extension)
/**
如何回调:block - iOS 开发中,block最多的用途就是在异步执行完成之后,通过参数回调通知调用方结果!
*/
- (void)cz_cornerImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor completion:(void (^)(UIImage *))completion {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSTimeInterval start = CACurrentMediaTime();
// 1. 利用绘图,建立上下文
UIGraphicsBeginImageContextWithOptions(size, YES, 0);
CGRect rect = CGRectMake(0, 0, size.width, size.height);
// 2. 设置填充颜色
[fillColor setFill];
UIRectFill(rect);
// 3. 利用 贝赛尔路径 `裁切 效果
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
[path addClip];
// 4. 绘制图像
[self drawInRect:rect];
// 5. 取得结果
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
// 6. 关闭上下文
UIGraphicsEndImageContext();
NSLog(@"%f", CACurrentMediaTime() - start);
// 7. 完成回调
dispatch_async(dispatch_get_main_queue(), ^{
if (completion != nil) {
completion(result);
}
});
});
}
@end