2016-11-07 21 views
2

我試圖讓UIView顯示鋸齒形底邊。像http://www.shutterstock.com/pic-373176370/stock-vector-receipt-vector-icon-invoice-flat-illustration-cheque-shadow-bill-with-total-cost-amount-and-dollar-symbol-abstract-text-receipt-paper-isolated-on-green.html?src=zMGBKj_5etMCcRB3cKmCoA-1-2作爲掩碼的CAShaperLayer只顯示UIView的四分之一

我有創建一個路徑並設置爲掩碼,但它顯示爲視圖的1/4的方法。我需要設置其他東西嗎?看起來像一個視網膜問題或協調問題,但不知道哪一個。

func layoutZigZag(bounds: CGRect) -> CALayer { 
    let maskLayer = CAShapeLayer() 
    maskLayer.bounds = bounds 
    let path = UIBezierPath() 

    let width = bounds.size.width 
    let height = bounds.size.height 

    let topRight = CGPoint(x: width , y: height) 
    let topLeft = CGPoint(x: 0 , y: height) 
    let bottomRight = CGPoint(x: width , y: 0) 
    let bottomLeft = CGPoint(x: 0 , y: 0) 

    let zigzagHeight: CGFloat = 10 
    let numberOfZigZag = Int(floor(width/23.0)) 
    let zigzagWidth = width/CGFloat(numberOfZigZag) 

    path.move(to: topLeft) 
    path.addLine(to: bottomLeft) 

    // zigzag 
    var currentX = bottomLeft.x 
    var currentY = bottomLeft.y 
    for i in 0..<numberOfZigZag { 
     let upper = CGPoint(x: currentX + zigzagWidth/2, y: currentY + zigzagHeight) 
     let lower = CGPoint(x: currentX + zigzagWidth, y: currentY) 

     path.addLine(to: upper) 
     path.addLine(to: lower) 

     currentX += zigzagWidth 
    } 

    path.addLine(to: topRight) 
    path.close() 

    maskLayer.path = path.cgPath 
    return maskLayer 
} 

and 

let rect = CGRect(x: 0, y: 0, width: 320, height: 400) 
let view = UIView(frame: rect) 
view.backgroundColor = UIColor.red 
let zigzag = layoutZigZag(bounds: rect) 
view.layer.mask = zigzag 

路徑看起來正確

Path look correct

結果認爲

Result

+0

檢查'contentScale'如果您層(它已被分配到後風景)。視網膜顯示可能無法正確設置爲2.0。如果是這樣,圖層的座標將被解釋爲物理像素而不是邏輯點。 – Codo

回答

1

變化maskLayer.bounds = bounds的1/4到maskLayer.frame = bounds

更新:

倒掛是因爲UI和CG,我們正在創造UIBezierPath路徑和轉換該路徑作爲一個CGPath(maskLayer.path = path.cgPath)之間的差異。首先我們要知道區別,其中CGPath is Quartz 2D原點位於左下角UIBezierPath is UIKit原點位於左上角。根據你的代碼,當我們轉換爲CGPath(原點在左下角)時,應用的座標按照左上方即UIBezierPath進行倒置。所以更改代碼如下,以獲得所需的效果。

let topRight = CGPoint(x: width , y: 0) 
    let topLeft = CGPoint(x: 0 , y: 0) 
    let bottomLeft = CGPoint(x: 0 , y: (height - zigzagHeight)) 

石英二維座標系

enter image description here

UIBezierPath座標系

enter image description here

+0

它的工作表示感謝!你能解釋一下這個問題嗎?我假設frame是零,因爲我沒有設置它,但爲什麼它顯示爲這樣的1/4矩形。 – sarunw

+0

結果視圖仍然顛倒(路徑看起來是正確的),但是當應用遮罩時它會顛倒過來。這是正常的嗎?處理這個問題的正確方法是什麼? – sarunw

+0

@sarunw請檢查更新後的答案,並檢查它以瞭解框架和界限之間的區別。 http://stackoverflow.com/questions/1210047/cocoa-whats-the-difference-between-the-frame-and-the-bounds – Jeyamahesan

相關問題