2014-10-10 59 views
0

我想重現書中的一個例子iOS編程:大Nerd牧場指南第4版CGGradient和路徑剪輯:剪輯周圍的奇怪邊框

請注意,我在Swift中重寫了本書中的所有Obj-C代碼。

是一個挑戰,這本書需要繪製這個三角形梯度,採用核芯顯卡:

enter image description here

但是當我運行我的代碼,我注意到一個豆蔻灰色邊框包圍的三角形:

enter image description here

我不明白爲什麼....這是我的代碼:

.... 
    // draw circles 
    UIColor.grayColor().setStroke() 
    path.stroke() 

    let logoImg = UIImage(named: "logo.png") 
    let realSize:CGSize = logoImg.size.halve() // get a /2 CGSize in order to calculate non-retina size 

    let gradientLocations:[CGFloat] = [0, 1] 
    let gradientColors:[CGFloat] = [0, 1, 0, 1, 
            1, 1, 0, 1] 
    let colorSpace = CGColorSpaceCreateDeviceRGB() 
    let gradient = CGGradientCreateWithColorComponents(colorSpace, gradientColors, gradientLocations, 2) 

    let gradientClipPath = UIBezierPath() 
    gradientClipPath.moveToPoint(CGPoint(x: center.x - realSize.width/2, y: center.y + realSize.height/2 + 30)) 
    gradientClipPath.addLineToPoint(CGPoint(x: center.x + realSize.width/2, y: center.y + realSize.height/2 + 30)) 
    gradientClipPath.addLineToPoint(CGPoint(x: center.x, y: center.y - realSize.height/2 - 30)) 
    gradientClipPath.addLineToPoint(CGPoint(x: center.x - realSize.width/2, y: center.y + realSize.height/2 + 30)) 
    gradientClipPath.fill() 

    // draw gradient 
    CGContextSaveGState(currContext) 
    gradientClipPath.addClip() 
    CGContextDrawLinearGradient(currContext, gradient, CGPoint(x: 0, y: center.y - realSize.height/2 - 30), CGPoint(x: 0, y: center.y + realSize.height/2 + 30), 0) 
    CGContextRestoreGState(currContext) 

    // draw logo with drop shadow 
    .... 

設定行程清除或其他顏色沒有效果。邊框仍然存在,它仍然是灰色的。

+0

'gradientClipPath.fill()'是否意味着在代碼中?我認爲這是一個錯誤。如果不是這樣,我無法真正幫助對不起,現在我總是使用'CAShapeLayer',並且在Core Graphics中練習過。注意:你真的應該避免在真實世界的項目中使用核心圖形。通常'CAShapeLayer'對於繪製貝塞爾路徑更好。 – 2014-10-10 03:06:46

+0

我認爲'fill()'應該在那裏,因爲它會觸及漸變將被繪製的區域...不是?請注意,這是本書中的一個挑戰,所以我自己寫了部分代碼。感謝您提供關於CG的建議。 – Teejay 2014-10-10 08:14:14

+0

嘗試填寫,我認爲這是錯誤的部分。如果你不填滿它有幫助嗎? – 2014-10-10 10:03:21

回答

0

在繪製漸變之前,不需要填充漸變路徑。刪除此行:

gradientClipPath.fill()