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

时间:2011-08-25 21:14:48

标签: iphone objective-c ios

我正在尝试为我正在构建的应用程序之一制作一个很酷的效果,并且宁愿不使用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画一个圆圈。

3 个答案:

答案 0 :(得分: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 :(得分: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;  
}

答案 2 :(得分:1)

以下方法如何: 使用原始顶部的第二个UIImageView,它包含您想要框架的图像。第二个UIImageView具有图片框架图像的可伸缩版本,因此如果原始图像的尺寸发生变化,您的相框可能会发生变化。

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

您可以使用UIImage的stretchableImageWithLeftCapWidth方法创建相框图像的可伸缩版本。