1

I have an UIImage and I need to make it round with white border. I don't need UIImageView for this.

How do you do this?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
DenFav
  • 2,683
  • 1
  • 18
  • 27

2 Answers2

9

You can use QuartzCore functions to create an image context, draw the clipped image, and then stroke the path:

- (UIImage *)imageWithBorderAndRoundCornersWithImage:(UIImage *)image lineWidth:(CGFloat)lineWidth cornerRadius:(CGFloat)cornerRadius {
    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale);
    CGRect rect = CGRectZero;
    rect.size = image.size;
    CGRect pathRect = CGRectInset(rect, lineWidth / 2.0, lineWidth / 2.0);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:cornerRadius];

    CGContextBeginPath(context);
    CGContextAddPath(context, path.CGPath);
    CGContextClosePath(context);
    CGContextClip(context);

    [image drawAtPoint:CGPointZero];

    CGContextRestoreGState(context);

    [[UIColor whiteColor] setStroke];
    path.lineWidth = lineWidth;
    [path stroke];

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

    return finalImage;
}

That takes:

without border

And makes:

enter image description here

Rob
  • 415,655
  • 72
  • 787
  • 1,044
1

You need a UIImageView to do this in a simple way. Rounded (Corner Radius) and borders thickness / color are typical properties of the CALayer of a UIView. Simplest way is to have a UIImageView or maybe some other type of UIView to implement this.

Something like that might do the job.

let myImg = UIImage(named: "some_image.png")
let imgView = UIImageView(image: myImg)
imgView.clipsToBounds = true
imgView.layer.cornerRadius = 0.5*imgView.frame.width
imgView.layer.borderWidth = 5.0 //Or some other value
imgView.layer.borderColor = UIColor.whiteColor().CGColor
Joe
  • 2,386
  • 1
  • 22
  • 33
  • This will resize the image to the size of the image view and the scale of the device upon which you do this. That's fine if that is the desired effect, but the OP should be aware of this. Also note that this technique can sometimes result in undesirable artifacts along the outside edges of the rounded corners. You can solve this by masking the image view. See http://stackoverflow.com/a/30125297/1271826. – Rob Mar 20 '16 at 20:50