如何用圆圈遮盖方形图像并在图像周围放置黑色边框

时间:2012-10-26 05:40:34

标签: objective-c ios mask uibezierpath

我有一个40x40的方形图像,我希望通过剪裁来制作,但也在图像周围放置一个黑色的5像素边框。

我有以下屏蔽方形图像,所以它现在是圆形

 UIImage *image = self.imageView.image;
        CGSize imageSize = image.size;
        CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);

        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
        // Create the clipping path and add it
        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageRect];
        [path addClip];


        [image drawInRect:imageRect];
        UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        self.imageView.image = roundedImage;

但是现在我还需要在它周围添加一个圆形边框。我是否需要一条新路径,或者我可以在上面的代码中找到一条路径?

1 个答案:

答案 0 :(得分:12)

在代码中添加以下三行(使用您想要的任何颜色和笔触宽度):

CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor] CGColor]);
[path setLineWidth:50.0f];
[path stroke];

所以它变成了:

UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Create the clipping path and add it
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageRect];
[path addClip];
[image drawInRect:imageRect];

CGContextSetStrokeColorWithColor(ctx, [[UIColor greenColor] CGColor]);
[path setLineWidth:50.0f];
[path stroke];

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

self.imageView.image = roundedImage;