我肯定错过了Core Graphics上下文的某些部分,并且无法自行解决问题。 这是我在Xcode Playground中的代码
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 :(得分:0)
您正在体验无限递归。我不知道为什么,但它与你的测试程序有关。问题在于您的测试方式 - 而不是在您的代码中。 不要在操场上测试这种代码。游乐场不是现实。
(我可以概括并说,不要使用游乐场。他们是魔鬼的作品。但我不会。哎呀,我是否大声说出来了?)
无论如何,我将您的代码复制并粘贴到一个新的应用程序项目中(并且我取消注释了drawGrad
行),它运行得很好,没有您描述的那种递归问题。
请注意,您需要将视图放入界面中,以便它可以执行任何操作。为了做到这一点,我添加了这一行:
self.view.addSubview(myView)
除此之外,我的代码与你的相同,没有问题。