编辑:
我想要实现的是在第二次调用 drawRect 时跳过对 firstDraw() 的调用。这样做的原因是,在我的真实代码中,我有很多数据点和线要绘制,所以我认为如果我回收以前绘制的东西,我可以优化性能。这对 CoreGraphics 有可能吗?
我希望能够在 UIView 上执行多个绘图,而不必重新绘制我已经绘制的内容。
下面的代码将以 2.4 秒的时间间隔执行两次绘制。第一次调用后,我使用CGContextSaveGState保存状态。在第二次调用中,我检索当前图形上下文,然后添加一些行。然而,这似乎失败了,因为似乎先前的上下文丢失了。
我得到什么:
这是我在第一次抽奖时得到的:
这是我在第二次通话后得到的:
这反而是我在第二次通话后想要得到的:
这是代码:
import UIKit
class GraphView: UIView {
var count : Int = 0
override func drawRect(rect: CGRect) {
if ( count == 0){
firstDraw()
NSTimer.scheduledTimerWithTimeInterval(2.4, target: self, selector: "setNeedsDisplay", userInfo: nil, repeats: false)
count++
}
else{
addLinesToDraw()
}
}
func firstDraw(){
// Drawing code
let context = UIGraphicsGetCurrentContext()
CGContextMoveToPoint(context, 50, 50);
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0);
CGContextSetRGBFillColor(context, 0, 0.0, 0.0, 1.0);
CGContextAddLineToPoint(context, 60, 60);
CGContextMoveToPoint(context, 150, 150);
CGContextAddLineToPoint(context, 110, 90);
CGContextSetLineWidth(context, 2);
CGContextStrokePath(context);
// Draw a Point as a small square
CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1.0);
CGContextSetRGBFillColor(context, 0.5, 0.5, 0.5, 1.0);
//NSLog(@"Drawing rect at point [x: %i, y: %i]", xPosition+resolution, pressureIntValue);
CGContextFillRect(context, CGRectMake(0, 0, 10, 10));
CGContextAddRect(context, CGRectMake(0, 0, 10, 10));
CGContextStrokePath(context);
CGContextSaveGState(context)
}
func addLinesToDraw(){
// Drawing code
let context = UIGraphicsGetCurrentContext()
CGContextMoveToPoint(context, 30, 60);
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0);
CGContextSetRGBFillColor(context, 0, 0.0, 0.0, 1.0);
CGContextAddLineToPoint(context, 20, 20);
CGContextMoveToPoint(context, 120, 250);
CGContextAddLineToPoint(context, 110, 90);
CGContextSetLineWidth(context, 2);
CGContextStrokePath(context);
// Draw a Point as a small square
CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1.0);
CGContextSetRGBFillColor(context, 0.5, 0.5, 0.5, 1.0);
//NSLog(@"Drawing rect at point [x: %i, y: %i]", xPosition+resolution, pressureIntValue);
CGContextFillRect(context, CGRectMake(20, 30, 10, 10));
CGContextAddRect(context, CGRectMake(20, 30, 10, 10));
CGContextStrokePath(context);
CGContextSaveGState(context)
}
}