Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mask a square image with a circle and also put a black border around the image

I have a square image 40x40 that I want to make round via clipping, but also put a black 5 pixel border around the image.

I have the following which is masking the square image so its now round

 UIImage *image = self.imageView.image;
        CGSize imageSize = image.size;
        CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);

        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
        // Create the clipping path and add it
        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageRect];
        [path addClip];


        [image drawInRect:imageRect];
        UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        self.imageView.image = roundedImage;

But now I need to also add a round border around it. Do I need a new path or can I just tack onto the one one in the code above?

like image 609
jdog Avatar asked Dec 15 '22 18:12

jdog


1 Answers

Add the following three lines in your code (with whatever color and stroke width you want):

CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor] CGColor]);
[path setLineWidth:50.0f];
[path stroke];

So it becomes:

UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Create the clipping path and add it
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageRect];
[path addClip];
[image drawInRect:imageRect];

CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor] CGColor]);
[path setLineWidth:50.0f];
[path stroke];

UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.imageView.image = roundedImage;
like image 130
atxe Avatar answered Mar 08 '23 23:03

atxe