沿着UIImage圈添加白色边框

adi*_*dit 1 iphone objective-c ipad ios

我使用掩码生成了一个圆形UIImage,如下所示(其中masked_circle是黑色圆圈):

CGContextRef context = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    UIImage *maskImage = [UIImage imageNamed:@"masked_circle.png"];
    CGImageRef maskImageRef = [maskImage CGImage];

    // create a bitmap graphics context the size of the image
    CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);

    CGFloat ratio = 0;
    ratio = maskImage.size.width/ self.image_.size.width;

    if(ratio * self.image_.size.height < maskImage.size.height) {
        ratio = maskImage.size.height/ self.image_.size.height;
    }

    CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
    CGRect rect2  = {{-((self.image_.size.width*ratio)-maskImage.size.width)/2 , -((self.image_.size.height*ratio)-maskImage.size.height)/2}, {self.image_.size.width*ratio, self.image_.size.height*ratio}};

    CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
    CGContextDrawImage(mainViewContentContext, rect2, self.image_.CGImage);

    CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
    CGContextRelease(mainViewContentContext);

    UIImage *theImage = [UIImage imageWithCGImage:newImage];
Run Code Online (Sandbox Code Playgroud)

在此之后我想在圆形图像周围添加1px白色边框,我该怎么办?

Mic*_*ael 5

这是一个更简单的解决方案,可以将任何视图,特别是UIImageView转换为具有不同大小和颜色边框的圆圈.这当然假设您正在处理像图标一样的方形图像.

#import <UIKit/UIKit.h>

@interface UIView (Shapes)
- (void)makeCircle;
- (void)makeCircleWithBorderColor:(UIColor *) color Width:(CGFloat) width;
@end


@implementation UIView (Shapes)

- (void)makeCircle {
    CALayer *lyr = self.layer;
    lyr.masksToBounds = YES;
    lyr.cornerRadius = self.bounds.size.width / 2; // assumes image is a square
}

- (void)makeCircleWithBorderColor:(UIColor *) color Width:(CGFloat) width {
    [self makeCircle];
    CALayer *lyr = self.layer;
    lyr.borderWidth = width;
    lyr.borderColor = [color CGColor];
}
@end
Run Code Online (Sandbox Code Playgroud)