为UIView任意角设置圆角

来源:互联网 发布:网络订票时间限制 编辑:程序博客网 时间:2024/05/17 06:36

圆角在苹果的世界时随处可见的。为视图设置圆角在开发iOS当中是经常要做的事情。要为UIView对象设置圆角也是非常简单地事情。

    view.layer.cornerRadius = 10;

这样一句代码就轻松为一个view的四个角设置了圆角。 当我们需要为view任意一个角设置圆角的时候,需要怎么办呢?有一个方法就是通过layer.mask,也就是遮罩。加上UIBezierPath的+ (UIBezierPath *)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii的这个方法就可以轻松添加圆角遮罩了。

UIRectCorner

UIRectCorner的定义如下:

typedef NS_OPTIONS(NSUInteger, UIRectCorner) {      UIRectCornerTopLeft     = 1 << 0,    UIRectCornerTopRight    = 1 << 1,    UIRectCornerBottomLeft  = 1 << 2,    UIRectCornerBottomRight = 1 << 3,    UIRectCornerAllCorners  = ~0UL};

例子

下面代码就是为一个view三个角设置圆角。

- (void)layoutSubviews{    [super layoutSubviews];    CGFloat corner = 50;    CAShapeLayer *shapeLayer = [CAShapeLayer layer];    shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(corner, corner)].CGPath;    self.layer.mask = shapeLayer;}

运行如下:

image


转自:http://supermao.cn/wei-uiviewren-yi-jiao-she-zhi-yuan-jiao/

0 0