为UIView任意角设置圆角

空之境界 2016-02-20 11:43:11 累计浏览 2,734 次

为UIView任意角设置圆角

   圆角在苹果的世界时随处可见的。为视图设置圆角在开发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;
}

   运行如下:

   为UIView任意角设置圆角

同分类推荐文章

  1. 被拆掉的 NSHostingView 还会再建一次 View (2026-11-14 04:40:02)
  2. OPPO Watch X3 Mini 表盘魔改过程记录 (2026-11-14 03:40:02)
  3. 宜家 Matter 智能家居终于要来了?在中国市场它将如何破局 (2026-10-29 17:40:42)

查看更多 移动开发 文章 →

建议继续学习

  1. App的成本 (累计阅读 7,895)
  2. iPhone下的libcurl with SSL for iOS (累计阅读 6,671)
  3. iOS的定位原理揭秘 (累计阅读 6,223)
  4. iOS内存暴增问题追查与使用陷阱 (累计阅读 6,119)
  5. IOS APP设计流程 (累计阅读 5,400)
  6. 在Visual Studio中使用MonoTouch开发iOS应用程序(上):环境配置 (累计阅读 5,377)
  7. iOS push服务 (累计阅读 5,183)
  8. 有关思维,有关Ipad一个Bug的故事 (累计阅读 5,015)
  9. IPhone上的邮件推送 (累计阅读 4,991)
  10. 手机交互设计资料 (累计阅读 4,761)