带圆角和边框的图像

时间:2013-12-18 13:29:18

标签: objective-c ios7 uikit

尝试获取带圆角和笔划的图像, 但有些事情我做错了,因为应用程序在此期间挂起:

- (UIImage *)roundedCornerImage:(NSInteger)radius{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);

    CGRect box = CGRectInset((CGRect){CGPointZero, self.size}, self.size.width * 0.9f, self.size.height * 0.9f);
    UIBezierPath *ballBezierPath = [UIBezierPath bezierPathWithOvalInRect:box];

    [[UIColor blackColor] setStroke];
    [ballBezierPath setLineWidth:4.0];
    [ballBezierPath stroke];

    [[UIBezierPath bezierPathWithRoundedRect:(CGRect){CGPointZero, self.size}
                                cornerRadius:radius]addClip];

    [self drawInRect:(CGRect){CGPointZero, self.size}];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

2 个答案:

答案 0 :(得分:3)

忘记搞乱图层,它是滚动视图中的性能杀手。只需生成一个新图像:

+(UIImage *)makeRoundedImage:(UIImage *)image withRadius:(CGFloat)radius
{
    CGRect itemFrame = CGRectMake(0, 0, radius*2, radius*2);

    // The source image
    UIImageView *imageView = [UIImageView new];
    imageView.frame = itemFrame;
    imageView.contentMode = UIViewContentModeScaleToFill;
    [imageView setImage:image];
    imageView.layer.cornerRadius = radius;
    imageView.layer.masksToBounds = YES;

    // Make an image of our client item
    UIGraphicsBeginImageContextWithOptions(itemFrame.size, NO, 0.0);
    [imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *returnImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Fini
    return returnImage;
}

答案 1 :(得分:2)

只需使用

[imageView.layer setCornerRadius:5.0f];
[imageView.layer setBorderWidth:5.0f];

不要忘记@import Quartzcore;