在UIImage周围放置一个圆形框架的最简单方法

4
我是一个有用的助手,我可以为你翻译文本。以下是需要翻译的内容:

我正在尝试为我正在构建的应用程序制作一个很酷的效果,而且不想深入drawRect函数。 你们能想到一种简单的方法来在UIImage周围放置一个漂亮的圆形边框吗? 它应该看起来像一个圆形图片框架。

这是我目前正在使用的:

CGFloat radius = self.layer.bounds.size.width / 2;

    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.frame = self.layer.bounds;
    [mask setFillColor:[[UIColor whiteColor] CGColor]];

    CGFloat width = self.layer.bounds.size.width;
    CGFloat height = self.layer.bounds.size.height;
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, width, 0);
    CGPathAddLineToPoint(path, NULL, width, height - radius);
    CGPathAddCurveToPoint(path, NULL, width, height, width - radius, height, width - radius, height);
    CGPathAddLineToPoint(path, NULL, 0, height);
    CGPathAddLineToPoint(path, NULL, 0, radius);
    CGPathAddCurveToPoint(path, NULL, 0, 0, radius, 0, radius, 0);
    CGPathCloseSubpath(path);
    [mask setPath:path];
    CGPathRelease(path);

    self.layer.mask = mask; 

    [self setNeedsDisplay];

我的UIImage被封装在一个UIView中(self是一个UIView)。我希望它能在我的UIView周围画一个圆圈。


你是在问如何在不使用视图的情况下绘制图像,还是在问是否有可能在不实际绘制到图像上的情况下绘制图像? - Maz
我正在尝试在我的图像周围画一个圆形。 - Rob
3个回答

8

最好的方法是使用QuartzCore。

基本上,您需要包含QuartzCore框架,然后创建一个UIView来放置您的图像,并将其角落变圆,并将其clipsToBounds属性设置为YES。

示例:

#include <QuartzCore/QuartzCore.h>

//More code stuff

UIView *newView = [[UIView alloc] initWithFrame:frame];
newView.clipsToBounds = YES;
newView.layer.cornerRadius = 10;
[newView addSubview:imageView];

1
我发现这种方法唯一的问题是,如果你想在图像上添加阴影,你会遇到麻烦,因为你必须使用clipToBounds。 - Jarsen
1
你关于那个遇到麻烦的说法是完全正确的。这就是为什么在我的评论中我说,“...创建一个 UIView 来放置你的图片...”,在某些情况下这并不是完美的答案,但它确实让你达到了想要的效果。 - Pudgeball

5

您可以在UIImageView的图层上使用蒙版,或者只需将圆角半径设置为高度的一半。 在任何情况下,请确保 #import <QuartzCore/QuartzCore.h>


myImageView.layer.cornerRadius = myImageView.bounds.size.width / 2;

示例掩码以使两个圆角(更改为将其替换为圆形):

+ (void) applyTwoCornerMask: (CALayer *) layer withRadius: (CGFloat) radius {
    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.frame = layer.bounds;
    [mask setFillColor:[[UIColor blackColor] CGColor]];

    CGFloat width = layer.bounds.size.width;
    CGFloat height = layer.bounds.size.height;
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, width, 0);
    CGPathAddLineToPoint(path, NULL, width, height - radius);
    CGPathAddCurveToPoint(path, NULL, width, height, width - radius, height, width - radius, height);
    CGPathAddLineToPoint(path, NULL, 0, height);
    CGPathAddLineToPoint(path, NULL, 0, radius);
    CGPathAddCurveToPoint(path, NULL, 0, 0, radius, 0, radius, 0);
    CGPathCloseSubpath(path);
    [mask setPath:path];
    CGPathRelease(path);

    layer.mask = mask;  
}

由于某些原因,这对我来说不起作用。以下是代码:代码无法适应评论,请检查编辑 - Rob

1
以下是一种方法: 使用第二个UIImageView,它位于原始图像上方,具有您想要框定的图像。这个第二个UIImageView具有可拉伸版本的图片框架图像,因此如果原始图像更改大小,则可以更改图片框架。

不易重复使用,但很简单。

您将使用UIImage的stretchableImageWithLeftCapWidth方法创建可拉伸版本的图片框架图像。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接