钻石般的UIView

时间:2016-04-22 21:00:36

标签: ios swift uiview cornerradius

我正在尝试创建一个带有像钻石形状一样的角的UIView,如图所示:

diamond

我熟悉四舍五入的角落:

myView.layer.cornerRadius = 10

然而,我想要一个不同的形状。我怎么能创造这种效果?谢谢你的帮助!

1 个答案:

答案 0 :(得分:3)

解决此类问题的最佳方法是使用CAShapeLayer。这就是可行的方法:将它粘贴到游乐场,看看它是如何从角落剪掉的。

import UIKit
import XCPlayground

extension UIView {
    func maskCorners(inset: CGFloat) {
        let path = UIBezierPath()
        path.moveToPoint(CGPoint(x: bounds.origin.x + inset,y: 0))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds) - inset,y: 0))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds), y: bounds.origin.y + inset))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds), y: CGRectGetMaxY(bounds) - inset))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds) - inset,y: CGRectGetMaxY(bounds)))
        path.addLineToPoint(CGPoint(x: bounds.origin.x + inset,y: CGRectGetMaxY(bounds)))
        path.addLineToPoint(CGPoint(x: 0,y: CGRectGetMaxY(bounds) - inset))
        path.addLineToPoint(CGPoint(x: 0,y: bounds.origin.y + inset))
        path.addLineToPoint(CGPoint(x: bounds.origin.x + inset,y: 0))

        let mask = CAShapeLayer()
        mask.frame = bounds
        mask.path = path.CGPath
        layer.mask = mask
    }
}

let diamond = UIView(frame: CGRect(x:0, y: 0, width: 100, height:100))
diamond.backgroundColor = UIColor.redColor()
XCPlaygroundPage.currentPage.liveView = diamond
diamond.maskCorners(25)