2017-08-02 68 views
0

我得爲我的視圖中創建一個面具佈局UIView的遮罩層,但我不能讓我想獲得創建使用CAShapeLayer()

@IBOutlet weak var viewToCrop: UIView! 
let angle = CGFloat(2*M_PI/3) 

func createMask() { 
    let mask = CAShapeLayer() 
    mask.frame = viewToCrop.layer.bounds 
    let heightButton = viewToCrop.frame.height 
    let lineWidth = -heightButton/tan(angle) 

    let width = viewToCrop.layer.frame.size.width 
    let height = viewToCrop.layer.frame.size.height 

    let path = CGPathCreateMutable() 
    CGPathMoveToPoint(path, nil, 0, 0) 
    CGPathAddLineToPoint(path, nil, width, 0) 
    CGPathMoveToPoint(path, nil, width - lineWidth, height) 
    CGPathAddLineToPoint(path, nil, lineWidth, height) 
    CGPathAddLineToPoint(path, nil, 0, 0) 

    mask.path = path 
    viewToCrop.layer.mask = mask 
} 

我需要建立這樣的數字結果:

enter image description here

但是運行代碼後,我得到的矩形。 我在做什麼錯?

P.S.我工作的一個傳統項目上斯威夫特2

+0

什麼價值角度在這裏? – agibson007

+0

60度@ agibson007 –

+0

也是爲什麼斯威夫特2? – agibson007

回答

1

我沒有斯威夫特2編譯器選項,但我要帶刺,希望得到您關閉。我認爲最重要的是路徑lineWidth需要被座標除以2。另外要注意的是,如果視圖的高度太大,那麼60太陡。我會建議根據百分比繪製它,除非你需要確切的角度。如果沒有Swift 2編譯器,我會盡我所能讓我知道。

@IBOutlet weak var viewToCrop: UIView! 
let angle = CGFloat(2*M_PI/3) 

func createMask() { 
    let mask = CAShapeLayer() 
    mask.frame = viewToCrop.layer.bounds 
    let heightButton = viewToCrop.frame.width 
    let lineWidth = -heightButton/tan(angle) 

    let width = viewToCrop.layer.frame.size.width 
    let height = viewToCrop.layer.frame.size.height 

    let path = CGPathCreateMutable() 
    CGPathMoveToPoint(path, nil, 0, 0) 
    CGPathAddLineToPoint(path, nil, width, 0) 
    CGPathMoveToPoint(path, nil, width - lineWidth/2, height) 
    CGPathAddLineToPoint(path, nil, lineWidth/2, height) 
    CGPathAddLineToPoint(path, nil, 0, 0) 

    mask.path = path 
    viewToCrop.layer.mask = mask 
    } 

結果 Result