繁体   English   中英

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

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

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

PS我需要画一幅画。

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;

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

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

结果:

前/后的例子

你试过这个吗?

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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM