指定UIView的特定角为圆角


  • 如果需要将UIView的4个角全部设为圆角,做法相当简单:
  1. 纯代码只需设置其Layer的cornerRadius属性即可(项目需要使用QuartzCore框架)
  1. xib上只需如图一那样设置就行了
指定UIView的特定角为圆角_第1张图片
图一
  • 若要指定某几个角(小于4个)为圆角而别的不变时,这种方法就不好用了。对于这种情况,Stackoverflow上提供了几种解决方案。其中最简单优雅的方案,就是使用UIBezierPath。下面给出一段示例代码。
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view2];

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds
                                               byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
                                                     cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame         = view.bounds;
maskLayer.path          = maskPath.CGPath;
view.layer.mask         = maskLayer;

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

  • UIRectCornerTopLeft
  • UIRectCornerTopRight
  • UIRectCornerBottomLeft
  • UIRectCornerBottomRight
  • UIRectCornerAllCorners

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


再一次感谢您花费时间阅读这篇文章!

微博: @Danny_吕昌辉
博客: SuperDanny

2015 年 08月 20日

你可能感兴趣的:(指定UIView的特定角为圆角)