天天看點

iOS UIImage生成高性能圓角圖檔

- (void)imageWihtSize:(CGSize)size radius:(CGFloat)radius backColor:(UIColor *)backColor completion:(void(^)(UIImage *image))completion{
    // 異步繪制裁切
    dispatch_async(dispatch_get_global_queue(, ), ^{
        // 利用繪圖建立上下文
        UIGraphicsBeginImageContextWithOptions(size, true, );
        CGRect rect = CGRectMake(, , size.width, size.height);
        // 填充顔色
        [backColor setFill];
        UIRectFill(rect);
        // 貝塞爾裁切
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
        [path addClip];
        [self drawInRect:rect];

        // 擷取結果
        UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
        // 關閉上下文
        UIGraphicsEndImageContext();
        // 主隊列回調
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(resultImage);
        });
    });
}