ios 将矩形图片裁剪成圆形图片
2015-09-21 12:11
477 查看
在ios中将一个正方形的图片裁剪成圆形的图片是一件非常容易的事情, 直接设置 imageView.layer.cornerRadius 这个属性, 再设置 imageView.clipsToBounds = YES 就可以了, 但是对于长方形的图片来说这个方式裁剪出来的就不是一个圆形的了, 而是个椭圆的. 解决这个问题就需要自己画 并且需要计算. 最终效果图如下:
tips: 如果是裁剪矩形的话, 是从图片中心的位置为圆心剪裁的.
代码如下:
@implementation UIImage (CF)
+ (UIImage*)circleImageWith: (NSString*)imageName borderWidth: (CGFloat)width borderColor: (UIColor*)color
{
UIImage* oldImage = [UIImage imageNamed:imageName];
CGFloat minLength = MIN(oldImage.size.width, oldImage.size.height);
CGFloat length = minLength + width * 2;
CGFloat centerX = length * 0.5;
CGFloat centerY = length * 0.5;
CGFloat bigRadius = length * 0.5;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(length, length), NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 画大圆
[color set];
CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(ctx);
// 画小圆
CGFloat smallRadius = minLength * 0.5;
CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
CGContextClip(ctx);
CGFloat imageX = centerX - oldImage.size.width * 0.5;
CGFloat imageY = centerY - oldImage.size.height * 0.5;
[oldImage drawInRect:CGRectMake(imageX, imageY, oldImage.size.width, oldImage.size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
tips: 如果是裁剪矩形的话, 是从图片中心的位置为圆心剪裁的.
代码如下:
@implementation UIImage (CF)
+ (UIImage*)circleImageWith: (NSString*)imageName borderWidth: (CGFloat)width borderColor: (UIColor*)color
{
UIImage* oldImage = [UIImage imageNamed:imageName];
CGFloat minLength = MIN(oldImage.size.width, oldImage.size.height);
CGFloat length = minLength + width * 2;
CGFloat centerX = length * 0.5;
CGFloat centerY = length * 0.5;
CGFloat bigRadius = length * 0.5;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(length, length), NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 画大圆
[color set];
CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(ctx);
// 画小圆
CGFloat smallRadius = minLength * 0.5;
CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
CGContextClip(ctx);
CGFloat imageX = centerX - oldImage.size.width * 0.5;
CGFloat imageY = centerY - oldImage.size.height * 0.5;
[oldImage drawInRect:CGRectMake(imageX, imageY, oldImage.size.width, oldImage.size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
相关文章推荐
- 整理iOS9适配中出现的坑(图文)
- iOS项目更新之升级Xcode7 & iOS9
- 正则表达式在iOS中的运用
- iOS cocoapods安装
- iOS中Bitcode的报错
- iOS 9部分问题
- <二>Copy和mutableCopy——iOS开发的疑惑
- IOS常用手势用法
- 【转】iOS深入学习(Block全面分析)
- IOS 记录一些用到的正则表达式
- ios 错误
- iOS模拟器卡在启动界面
- iOS开发日记21-7.0之后的图文混排
- 七牛如何安装ios sdk (强烈建议试使用cocoapods安装)
- iOS 之旅--自定义开始界面
- iOS runtime方法详解之属性操作
- OC项目总结
- 银联手机支付控件官方使用指南(ios版)
- iOS APNS device Token 是否会改变?
- XCODE6+ios8真机调试[转]