我创建此帖子以回答Create a UIView with rounded top edge上的暂停发布问题
问题是如何创建像这样的圆形UIView?
...而不是这样(2个圆角)
回答:https://stackoverflow.com/a/28075863/1952147
最佳答案
解决方案是将椭圆形和矩形与bezierPath组合在一起。
如果需要自定义更多曲线,可以添加高度偏移。
@implementation UIView (RoundedCorners)
-(void)setRoundedRectWithOvalWidthOffset:(CGFloat)offset {
CGRect bounds = self.bounds;
CGRect rectBounds = CGRectMake(bounds.origin.x,
bounds.origin.y + bounds.size.height/2,
bounds.size.width,
bounds.size.height/2);
UIBezierPath *rectPath = [UIBezierPath bezierPathWithRect:rectBounds];
//[rect addClip];
CGRect ovalBounds = CGRectMake(bounds.origin.x - offset/2,
bounds.origin.y,
bounds.size.width + offset,
bounds.size.height);
UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:ovalBounds];
//[oval addClip];
[rectPath appendPath:ovalPath];
// Create the shape layer and set its path
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.path = rectPath.CGPath;
// Set the newly created shape layer as the mask for the view's layer
self.layer.mask = maskLayer;
}
@end
Swift 3.0的代码
//MARK: - UIView Extension
extension UIView {
func setTopCurve(){
let offset = CGFloat(self.frame.size.height/4)
let bounds = self.bounds
let rectBounds = CGRect(x: bounds.origin.x, y: bounds.origin.y + bounds.size.height/2 , width: bounds.size.width, height: bounds.size.height / 2)
let rectPath = UIBezierPath(rect: rectBounds)
let ovalBounds = CGRect(x: bounds.origin.x - offset / 2, y: bounds.origin.y, width: bounds.size.width + offset, height: bounds.size.height)
let ovalPath = UIBezierPath(ovalIn: ovalBounds)
rectPath.append(ovalPath)
let maskLayer = CAShapeLayer.init()
maskLayer.frame = bounds
maskLayer.path = rectPath.cgPath
self.layer.mask = maskLayer
}
}
关于ios - 圆形顶部的UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075862/