iOS开发指定UIView的某几个角为圆角

来源:互联网 发布:autodesk的造型软件 编辑:程序博客网 时间:2024/06/06 14:20

在iOS开发中,我们经常会遇到View设置圆角的问题,如果需要将UIView的4个角全部都为圆角,做法相当简单,只需设置其Layer的cornerRadius属性即可(项目需要使用QuartzCore框架)。而若要指定某几个角(小于4)为圆角而别的不变时,这种方法就不好用了。如图:

Mou icon
Mou icon

对于后者这种情况,下面给出一种比较简单优雅的方案,就是使用UIBezierPath。

示例代码如下:

UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(100, 10, 80, 80)];testView.backgroundColor = [UIColor redColor];[self.view addSubview:testView];UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:testView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];maskLayer.frame = testView.bounds;maskLayer.path = maskPath.CGPath;testView.layer.mask = maskLayer;

其中,byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
指定了需要成为圆角的角。该参数是UIRectCorner类型的,可选的值有:

  • UIRectCornerTopLeft
  • UIRectCornerTopRight
  • UIRectCornerBottomLeft
  • UIRectCornerBottomRight
  • UIRectCornerAllCorners

从名字很容易看出来代表的意思,使用“|”来组合就好了。

原创粉丝点击