2014-11-02 54 views
1

我絕對缺少Core Graphics上下文的某些部分,無法自行清除所有內容。 這是我在Xcode遊樂場CoreGraphics和上下文中的旋轉和漸變

import UIKit 
class MyView08 : UIView { 

    override func drawRect(rect: CGRect) { 
     let cornerRaduis : CGFloat = 20 
     let pathRect = CGRectInset(self.bounds, 20, 20) 
     let rectanglePath = UIBezierPath(roundedRect: pathRect, cornerRadius: cornerRaduis) 
     var context = UIGraphicsGetCurrentContext() 
     CGContextSaveGState(context) 
     rotate(rectanglePath, context: context) 
     CGContextRestoreGState(context) 

     context = UIGraphicsGetCurrentContext() 
     CGContextSaveGState(context) 
    // drawGrad(rectanglePath, context: context) 
     CGContextRestoreGState(context) 
    } 

    func rotate(rectanglePath : UIBezierPath, context : CGContext) { 
     let rotation = CGAffineTransformMakeRotation(CGFloat(M_PI)/4.0) 
     CGContextConcatCTM(context, rotation) 
     UIColor.greenColor().setFill() 
     rectanglePath.fill() 

    } 

    func drawGrad (rectanglePath : UIBezierPath, context : CGContext) { 
     let startColor = UIColor.redColor() 
     let endColor = UIColor.greenColor() 
     let gradientColors : CFArray = [startColor.CGColor, endColor.CGColor] 
     let gradientLocations : [CGFloat] = [0.0, 1.0] 
     let colorSpace = CGColorSpaceCreateDeviceRGB() 
     let gradient = CGGradientCreateWithColors(colorSpace, gradientColors, gradientLocations) 
     let topPoint = CGPointMake(self.bounds.size.width/2, 20) 
     let bottomPoint = CGPointMake(self.bounds.size.width/2, self.bounds.size.height - 20) 

     rectanglePath.addClip() 
     CGContextDrawLinearGradient(context, gradient, bottomPoint, topPoint, 0) 
    } 
} 

let myViewRect = CGRect(x: 0, y: 0, width: 300, height: 300) 
let myView = MyView08(frame: myViewRect) 

代碼如果我取消這條線

drawGrad(rectanglePath, context: context) 

一切都很糟糕,Xcode中嘗試執行代碼近2萬次之後,它失敗。 我想旋轉矩形並繪製漸變。

回答

0

您正在經歷無限遞歸。我不知道爲什麼,但它與你的測試程序有關。問題在於你如何測試 - 而不是在你的代碼中。 不要在操場上測試這種代碼。遊樂場不是現實。

(我可以概括說,永遠不要使用操場。他們是魔鬼的工作。但我不會。哎呀,我才大聲說出來?)

無論如何,我將你的代碼複製並粘貼到一個新的應用程序項目中(並且我取消了註釋drawGrad行),它運行得很好,沒有你描述的那種遞歸問題。

請注意,您需要將視圖放入界面才能執行任何操作。我加入這行,爲了做到這一點:

self.view.addSubview(myView) 

除此之外,我的代碼是相同你的,而且也沒有問題。

+0

所以,我正在做的事情? 保存上下文,進行循環,恢復上下文,保存上下文,使梯度,恢復上下文? – barsa4ever 2014-11-02 16:58:58

+0

我根本沒有想到你的意思是「對」。這取決於你想要做什麼。但從純粹形式的角度來看,你肯定沒有做錯什麼。走出操場,開始使用應用程序作爲測試牀;至少可以看到你的代碼是否給了你期望的_actual results_。我懷疑它是什麼,但這是一個完全不同的問題!現在,在一個操場上工作,你甚至沒有遇到現實 - 你無法測試所有。離開那裏。 – matt 2014-11-02 17:23:00