在项目中提供的图片是矩形的,现要改成圆角图片,于是找了一些资料,下面是添加圆角图片的方法
创建UIImage的分类UIImage+ImageRounderCorner
在UIImage+ImageRounderCorner.h
文件中
#import <UIKit/UIKit.h>@interface UIImage (ImageRounderCorner)/** 调用此方法,返回一个带有圆角的UIImage对象 * 参数一:圆角半径 * 参数二:图片的大小 */- (UIImage *)imageAddCornerWithRadius:(CGFloat)radius andSize:(CGSize)size;@end
在UIImage+ImageRounderCorner.m
文件中
#import "UIImage+ImageRounderCorner.h"@implementation UIImage (ImageRounderCorner)- (UIImage *)imageAddCornerWithRadius:(CGFloat)radius andSize:(CGSize)size { CGRect rect = CGRectMake(0, 0, size.width, size.height);// 创建一个基于位图的上下文(context),并将其设置为当前上下文,size为新创建的位图上下文大小 // opaque 透明开关 // scale 缩放因子 UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); // 拿到当前上下文对象 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 创建贝塞尔曲线 UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)]; // 添加路径 CGContextAddPath(ctx, path.CGPath); // 裁剪 CGContextClip(ctx); // 绘图 [self drawInRect:rect]; // 填充绘制 CGContextDrawPath(ctx, kCGPathFillStroke); // 从当前位图上下文的内容输出一个UIImage图片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); // 上下文栈pop出创建的context UIGraphicsEndImageContext(); return newImage;}@end
使用:
在控制器中导入 #import "UIImage+ImageRounderCorner.h"
- (void)viewDidLoad { [super viewDidLoad]; UIImage *image = [UIImage imageNamed:@"image"]; UIImage *cornerImage = [image imageAddCornerWithRadius: 50.0 andSize:CGSizeMake(50.0, 50.0)]; UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)]; [self.view addSubview:imageView];}
运行后,发现,将原有的矩形图片转换为了带圆角的图片。
联系客服