Skip to content

Instantly share code, notes, and snippets.

@meigesir
Last active March 30, 2017 05:50
Show Gist options
  • Save meigesir/677e95dcb749cb793e3aa5d25ed7a717 to your computer and use it in GitHub Desktop.
Save meigesir/677e95dcb749cb793e3aa5d25ed7a717 to your computer and use it in GitHub Desktop.
绘制具有圆角的图片(可以配置圆角半径、边框、填充色),用途:具有圆角效果的场景,节省性能,告别离屏渲染,用法:简单,比如只需要把生成的图片放到视图底部即可
/**
绘制具有圆角的图片(可以配置圆角半径、边框、填充色),
用途:具有圆角效果的场景,节省性能,告别离屏渲染,
用法:简单,比如只需要把生成的图片放到视图底部即可
@param radius 圆角大小
@param borderWidth 边框宽度
@param borderColor 边框颜色
@param fillColor 填充色(如果不需要,可以传入[UIColor clearColor])
@param size 图形上下文大小(绘制区域大小)
@return 生成的具有圆角的图片
*/
+ (UIImage *)drawRectWithRoundedCornerWithRadius:(CGFloat)radius borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor fillColor:(UIColor *)fillColor forContextSize:(CGSize)size
{
CGFloat halfOfBorderWidth = borderWidth / 2.0;
/*根据指定选项(Options)创建基于位图的上下文 */
UIGraphicsBeginImageContextWithOptions(size, false, [UIScreen mainScreen].scale);
CGContextRef ctx = UIGraphicsGetCurrentContext();
/*设置边框和填充色*/
CGContextSetLineWidth(ctx, borderWidth);
CGContextSetStrokeColorWithColor(ctx, borderColor.CGColor);
CGContextSetFillColorWithColor(ctx, fillColor.CGColor);
CGFloat width = size.width;
CGFloat height = size.height;
CGFloat realRadius = radius - halfOfBorderWidth;
/*绘制边框和圆角*/
CGContextMoveToPoint(ctx, width - halfOfBorderWidth, radius - halfOfBorderWidth); // 开始坐标右边开始
CGContextAddArcToPoint(ctx, width - halfOfBorderWidth , height - halfOfBorderWidth, width - radius - halfOfBorderWidth, height - halfOfBorderWidth, realRadius); // 右下角
CGContextAddArcToPoint(ctx, halfOfBorderWidth, height - halfOfBorderWidth, halfOfBorderWidth, height - radius - halfOfBorderWidth, realRadius); // 左下角
CGContextAddArcToPoint(ctx, halfOfBorderWidth, halfOfBorderWidth, width - halfOfBorderWidth - radius, halfOfBorderWidth, realRadius); // 左上角
CGContextAddArcToPoint(ctx, width - halfOfBorderWidth, halfOfBorderWidth, width - halfOfBorderWidth, radius + halfOfBorderWidth, realRadius); // 右上角
CGContextDrawPath(ctx, kCGPathFillStroke);
UIImage *out = UIGraphicsGetImageFromCurrentImageContext();
/*和UIGraphicsBeginImageContextWithOptions成对出现,从栈中移除基于位图的上下文*/
UIGraphicsEndImageContext();
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment