如果需要将UIView的4个角全部都为圆角,做法相当简单,只需设置其Layer的cornerRadius属性即可(项目需要使用QuartzCore框架)。而若要指定某几个角(小于4)为圆角而别的不变时,这种方法就不好用了。
对于这种情况,Stackoverflow上提供了几种解决方案。其中最简单优雅的方案,就是使用UIBezierPath。下面给出一段示例代码。
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.AccountInfoView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(30, 30)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.AccountInfoView.bounds;
maskLayer.path = maskPath.CGPath;
self.AccountInfoView.layer.mask = maskLayer;
其中,
byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight
指定了需要成为圆角的角。该参数是UIRectCorner类型的,可选的值有:
UIRectCornerTopLeft = 1 << 0,
UIRectCornerTopRight = 1 << 1,
UIRectCornerBottomLeft = 1 << 2,
UIRectCornerBottomRight = 1 << 3,
UIRectCornerAllCorners = ~0UL
从名字很容易看出来代表的意思,使用“|”来组合就好了。