Search code examples
objective-cios7uikit

Image with rounded corners and border


Trying to get an image with rounded corners and stroke, but there is something I do wrong, because app hangs during this:

- (UIImage *)roundedCornerImage:(NSInteger)radius{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);

    CGRect box = CGRectInset((CGRect){CGPointZero, self.size}, self.size.width * 0.9f, self.size.height * 0.9f);
    UIBezierPath *ballBezierPath = [UIBezierPath bezierPathWithOvalInRect:box];

    [[UIColor blackColor] setStroke];
    [ballBezierPath setLineWidth:4.0];
    [ballBezierPath stroke];

    [[UIBezierPath bezierPathWithRoundedRect:(CGRect){CGPointZero, self.size}
                                cornerRadius:radius]addClip];

    [self drawInRect:(CGRect){CGPointZero, self.size}];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

Solution

  • Forget messing with the layer, it's a performance killer in scroll views. Just generate a new image instead:

    +(UIImage *)makeRoundedImage:(UIImage *)image withRadius:(CGFloat)radius
    {
        CGRect itemFrame = CGRectMake(0, 0, radius*2, radius*2);
    
        // The source image
        UIImageView *imageView = [UIImageView new];
        imageView.frame = itemFrame;
        imageView.contentMode = UIViewContentModeScaleToFill;
        [imageView setImage:image];
        imageView.layer.cornerRadius = radius;
        imageView.layer.masksToBounds = YES;
    
        // Make an image of our client item
        UIGraphicsBeginImageContextWithOptions(itemFrame.size, NO, 0.0);
        [imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *returnImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        // Fini
        return returnImage;
    }