如何创建带边框的圆形图像(UIGraphics)?

时间:2014-08-22 14:00:22

标签: ios objective-c uigraphicscontext

如何创建带边框的圆形图像(UIGraphics)?

P.S。我需要画一幅画。

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;

3 个答案:

答案 0 :(得分:14)

听起来您想要将图像剪切成圆形。这是一个例子:

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;
}

结果:

example before/after

答案 1 :(得分:7)

你试过这个吗?

self.imageView.layer.borderColor = [UIColor greenColor].CGColor;
self.imageView.layer.borderWidth = 1.f;

您还需要

self.imageView.layer.corderRadius = self.imageView.frame.size.width/2;
self.imageView.clipsToBounds = YES;

答案 2 :(得分:1)

Swift 4版

extension UIImage {

    func circularImageWithBorderOf(color: UIColor, diameter: CGFloat, boderWidth:CGFloat) -> UIImage {
         let aRect = CGRect.init(x: 0, y: 0, width: diameter, height: diameter)
         UIGraphicsBeginImageContextWithOptions(aRect.size, false, self.scale)

         color.setFill()
         UIBezierPath.init(ovalIn: aRect).fill()

         let anInteriorRect = CGRect.init(x: boderWidth, y: boderWidth, width: diameter-2*boderWidth, height: diameter-2*boderWidth)
         UIBezierPath.init(ovalIn: anInteriorRect).addClip()

         self.draw(in: anInteriorRect)

         let anImg = UIGraphicsGetImageFromCurrentImageContext()!
         UIGraphicsEndImageContext()

         return anImg
     }
}