寫了一個將矩形圖片裁剪為圓角矩形的UIImage分類,可以避免大量的使用masksToBounds從而產(chǎn)生離屏渲染致讥。
1.思路
首先利用CoreGraphics繪制出一個圓角矩形的上下文,然后將圖片畫到上下文中练慕,最后通過上下文獲取裁剪好的圖片赃绊。
2.核心代碼
- (UIImage *)setCornerWithRadius:(CGFloat)radius andSize:(CGSize)size
{
//開啟圖形上下文
UIGraphicsBeginImageContext(size);
//繪制圓角矩形
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
//將Path添加到上下文中
CGContextAddPath(UIGraphicsGetCurrentContext(), path.CGPath);
//裁剪上下文
CGContextClip(UIGraphicsGetCurrentContext());
//將圖片繪制到上下文中
[self drawInRect:rect];
//設(shè)置繪制模式
CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathStroke);
//獲取圖片
UIImage *output = UIGraphicsGetImageFromCurrentImageContext();
//關(guān)閉上下文
UIGraphicsEndImageContext();
//返回裁剪好的圖片
return output;
}
3.源碼
源碼放在了github上,歡迎指正以现,覺得不錯的star一下呀!