2011-08-25 21 views
4

我试图为我正在构建的应用程序的其中一个创建一个很酷的效果,而不是用drawRect函数来解决这个问题。你们能想到一种简单的方法来在UIImage周围放置一个漂亮的圆形边框吗?它应该看起来像一个圆形的相框。围绕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封装(自我是一个UIView)。我期待它围绕我的UIView绘制一个圆圈。

+0

你问如何在不使用视图的情况下绘制图像,或者您是否可以绘制图像而不实际绘制图像? – Maz

+0

我想围绕我的图像画一个圆圈 – Rob

回答

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

由于某种原因,这不适合我。这里的代码:**代码将不会适合评论,请检查编辑** – Rob

1

如何以下方法: 使用第二的UIImageView是在具有要陷害图像的原始的顶部。这第二个UIImageView具有相框图像的可拉伸版本,以便在原始图像更改大小时可以更改相框。

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

您将使用UIImage的stretchableImageWithLeftCapWidth方法来创建图片帧图像的拉伸版本。