Skip to content

Instantly share code, notes, and snippets.

@zhaoyk
Created March 28, 2014 06:00
Show Gist options
  • Save zhaoyk/9826263 to your computer and use it in GitHub Desktop.
Save zhaoyk/9826263 to your computer and use it in GitHub Desktop.
生成一个带圆角的图片
/*
使用
view.layer.masksToBounds = YES; // slow
view.layer.cornerRadius = 4;
画圆角非常慢, 这个方法用来生成一张图片, 带圆角, 有背景色;
*/
+ (UIImage *)buttonBgImageWithSize:(CGSize)size color:(UIColor *)color cornerRadius:(CGFloat)cornerRadius {
// 不要用 UIGraphicsBeginImageContext(size);
// 第三个参数 0 表示 scale是屏幕的scale, 即使 2; 否则默认的是 1
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect bound = CGRectMake(0, 0, size.width, size.height);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:bound cornerRadius:cornerRadius];
[path addClip];
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, bound);
CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:0.85 alpha:1].CGColor);
// 偏移 0.25 可以画 1px 的线
UIBezierPath *border = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(bound, 0.25, 0.25) cornerRadius:cornerRadius];
[border setLineWidth:0.5];
[border stroke];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment