ios - 圆形顶部的UIView

标签 ios objective-c uiview uibezierpath

我创建此帖子以回答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/

相关文章:

ios - 分组 UITableview 中减少单元格

objective-c - [NSStepper setMinimum/setMaximum] 是否也设置该值?

ios - Swift:自定义 UIView.transition 有问题吗?

ios - 调整FontSizeToFitWidth 与SizeToFit

ios - 找不到 Cocoapods <RestKit/RestKit.h>

ios - GPUImageStillCamera 不工作

ios - 将旧的 CoreData 模型导入新项目

ios - ARkit如何从点击位置获取节点的精确点

ios - UIImageView 根据方向使用不同的图像

ios - 带有 ARC 错误 : [__NSCFString deviceOrientationDidChange:]: unrecognized selector 的 Cocoa Touch 项目