【发布时间】:2014-11-02 16:35:15
【问题描述】:
我肯定错过了 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 千次,然后就失败了。 我正在尝试旋转矩形并绘制渐变。
【问题讨论】:
标签: ios xcode swift core-graphics swift-playground