如何制作带圆角顶角和方角底角的UIView

时间:2011-06-27 22:25:56

标签: ios cocoa-touch uikit

我正在尝试获得带有圆角顶角和方形底角的视图,类似于分组的UITableViewCell的顶行。

任何人都知道一种简单的方法来绘制它而不使用背景图像吗?

4 个答案:

答案 0 :(得分:10)

我刚才读过这篇文章:

Just two rounded corners?

以及这个后续帖子:

Round two corners in UIView

我认为这些应该回答你的问题。

答案 1 :(得分:5)

使用 iOS 11 ,会引入一个名为CACornerMask的新结构。

使用此结构,您可以使用角落进行更改:topleft,topright,left left,right right。

Swift Sample

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

Objective-C示例

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

答案 2 :(得分:4)

Swift 4:iOS 11以后

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
    }
}

较早的iOS版本

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 :(得分:0)

客观C

使用视图角半径的iOS 11

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;
        }