typedef NS_ENUM(NSInteger,DWContentMode)//图片填充模式{ DWContentModeScaleAspectFit,//适应模式 DWContentModeScaleAspectFill,//填充模式 DWContentModeScaleToFill//拉伸模式};复制代码
///获取带圆角的图片/* radius:返回图片的圆角半径 圆角半径不可超过图片尺寸的1/2,否则按1/2处理 width:返回图片的宽度 返回的图片为一个宽高相等的矩形区域,但图片且居中显示 mode:返回图片的填充模式 适应模式:以原图片比例,能显示全部图片的最大尺寸进行填充 填充模式:以原图片比例,图片能充满容器的最小尺寸进行填充 拉伸模式:以拉伸图片能够使图片充满容器的尺寸进行填充 */-(UIImage *)dw_CornerRadius:(CGFloat)radius withWidth:(CGFloat)width contentMode:(DWContentMode)mode{ CGFloat originScale = self.size.width / self.size.height; CGFloat height = width / originScale; CGFloat scale = [UIScreen mainScreen].scale; CGFloat maxV = MAX(width, height); if (radius < 0) { radius = 0; } UIImage * image = nil; CGRect imageFrame; if (mode == DWContentModeScaleAspectFit) {//根据图片填充模式制定绘制frame if (originScale > 1) {//适应模式 imageFrame = CGRectMake(0, (width - height) / 2, width,height); } else { imageFrame = CGRectMake((height - width) / 2, 0, width, height); } } else if (mode == DWContentModeScaleAspectFill)//填充模式 { CGFloat newHeight; CGFloat newWidth; if (originScale > 1) { newHeight = width; newWidth = newHeight * originScale; imageFrame = CGRectMake( -(newWidth - newHeight) / 2, 0, newWidth, newHeight); } else { newWidth = height; newHeight = newWidth / originScale; imageFrame = CGRectMake(0, - (newHeight - newWidth) / 2, newWidth, newHeight); } } else//拉伸模式 { imageFrame = CGRectMake(0, 0, maxV, maxV); } UIGraphicsBeginImageContextWithOptions(CGSizeMake(maxV, maxV), NO, scale);//以最大长度开启图片上下文 CGContextRef context = UIGraphicsGetCurrentContext(); [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, maxV, maxV) cornerRadius:radius] addClip];//绘制一个圆形的贝塞尔曲线,并做遮罩 [self drawInRect:imageFrame];//在指定的frame中绘制图片 CGContextRotateCTM(context, M_PI_2); image = UIGraphicsGetImageFromCurrentImageContext();//从当前上下文中获取图片 UIGraphicsEndImageContext();//关闭上下文 return image;}复制代码