Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a circular image with border (UIGraphics)?

How to create a circular image with border (UIGraphics)?

P.S. I need to draw a picture.

code in viewDidLoad:

NSURL *url2 = [NSURL URLWithString:@"http://images.ak.instagram.com/profiles/profile_55758514_75sq_1399309159.jpg"];
NSData *data2 = [NSData dataWithContentsOfURL:url2];
UIImage *profileImg = [UIImage imageWithData:data2];

UIGraphicsEndImageContext();
// Create image context with the size of the background image.
UIGraphicsBeginImageContext(profileImg.size);
[profileImg drawInRect:CGRectMake(0, 0, profileImg.size.width, profileImg.size.height)];

// Get the newly created image.
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();

// Release the context.
UIGraphicsEndImageContext();

// Set the newly created image to the imageView.
self.imageView.image = result;
like image 788
SpaceInvader Avatar asked Nov 28 '22 15:11

SpaceInvader


1 Answers

It sounds like you want to clip the image to a circle. Here's an example:

static UIImage *circularImageWithImage(UIImage *inputImage,
    UIColor *borderColor, CGFloat borderWidth)
{

    CGRect rect = (CGRect){ .origin=CGPointZero, .size=inputImage.size };

    UIGraphicsBeginImageContextWithOptions(rect.size, NO, inputImage.scale); {

        // Fill the entire circle with the border color.
        [borderColor setFill];
        [[UIBezierPath bezierPathWithOvalInRect:rect] fill];

        // Clip to the interior of the circle (inside the border).
        CGRect interiorBox = CGRectInset(rect, borderWidth, borderWidth);
        UIBezierPath *interior = [UIBezierPath bezierPathWithOvalInRect:interiorBox];
        [interior addClip];

        [inputImage drawInRect:rect];

    }

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

    return outputImage;
}

Result:

example before/after

like image 81
rob mayoff Avatar answered Dec 15 '22 16:12

rob mayoff