Using cornerRadius on a UIImageView in a UITableViewCell

前端 未结 4 1094
情歌与酒
情歌与酒 2021-01-31 11:55

I\'m using a UIImageView for each of my UITableViewCells, as thumbnails. My code uses SDWebImage to asynchronously grab those images from

4条回答
  •  死守一世寂寞
    2021-01-31 12:11

    Non blocking solution

    As a follow up to Andrea's response, here is a function that will run his code in the background.

    + (void)roundedImage:(UIImage *)image
              completion:(void (^)(UIImage *image))completion {
        dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Begin a new image that will be the new image with the rounded corners
            // (here with the size of an UIImageView)
            UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
            CGRect rect = CGRectMake(0, 0, image.size.width,image.size.height);
    
            // Add a clip before drawing anything, in the shape of an rounded rect
            [[UIBezierPath bezierPathWithRoundedRect:rect
                                        cornerRadius:image.size.width/2] addClip];
            // Draw your image
            [image drawInRect:rect];
    
            // Get the image, here setting the UIImageView image
            UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    
            // Lets forget about that we were drawing
            UIGraphicsEndImageContext();
            dispatch_async( dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(roundedImage);
                }
            });
        });
    }
    

提交回复
热议问题