How can you make a UIView with rounded top corners and square bottom corners

无人久伴 提交于 2019-12-12 09:37:18

问题


I am trying to get a view with rounded top corners and square bottom corners, similar to the top row of a grouped UITableViewCell.

Anyone one know an easy way to draw it and not use a background image?


回答1:


I read this post a while ago:

Just two rounded corners?

and also this follow-up post:

Round two corners in UIView

I think these should answer your question.




回答2:


Swift 4: For iOS 11 onwards

override func viewDidLoad() {
    super.viewDidLoad()

    if #available(iOS 11.0, *) {
        self.viewToRound.clipsToBounds = true
        viewToRound.layer.cornerRadius = 20
        viewToRound.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    } else {
        // Fallback on earlier versions
    }
}

Earlier iOS Versions

override func viewDidLayoutSubviews() {
    self.viewToRound.clipsToBounds = true
    let path = UIBezierPath(roundedRect: viewToRound.bounds,
                            byRoundingCorners: [.topRight, .topLeft],
                            cornerRadii: CGSize(width: 20, height: 20))

    let maskLayer = CAShapeLayer()

    maskLayer.path = path.cgPath
    viewToRound.layer.mask = maskLayer
}



回答3:


With iOS 11 there is a new structure introduced named CACornerMask.

With this structure you can make changes with corners: topleft, topright, bottom left, bottom right.

Swift Sample:

myView.clipsToBounds = true
myView.layer.cornerRadius = 10
myView.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]

Objective-C Sample

self.view.clipsToBounds = YES;
self.view.layer.cornerRadius = 10;
self.view.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;



回答4:


Objective C

iOS 11 using view corner radius

if (@available(iOS 11.0, *)) {
            _parentView.clipsToBounds = YES;
            _parentView.layer.cornerRadius = 20;
            _parentView.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
        } else {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_parentView.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(20.0, 20.0)];

            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = _parentView.bounds;
            maskLayer.path  = maskPath.CGPath;
            _parentView.layer.mask = maskLayer;
        }


来源:https://stackoverflow.com/questions/6499663/how-can-you-make-a-uiview-with-rounded-top-corners-and-square-bottom-corners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!