我正在尝试在 iPhone 上绘制图形,但我希望图形能够快速更新,所以我真正想做的是将图形绘制到 a UIImageView
,然后在重复绘制方法时,清除旧图形并重新绘制它.
这是我的代码:
- (void)redraw {
canvas.image = nil;
UIGraphicsBeginImageContext(self.view.frame.size);
[canvas.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), 0, canvas.frame.size.height/2);
for (float i=0; i<500; i+=0.01) {
[self y:i];
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), ((i*200)-200), (y*200)+canvas.frame.size.height/2);
}
CGContextStrokePath(UIGraphicsGetCurrentContext());
canvas.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
这段代码在调用一次时完全按照我想要的方式工作。它显示以下曲线:
redraw
但是,当我为奇怪的事情添加计时器时,就会开始发生。当应用程序启动时,我得到了上图所示的曲线,但它立即变成了这条曲线(相同的曲线,只是看起来沿 x 轴拉伸得更多,而在 y 轴上更高(技术上更低):
和:
- (void)y:(float)x {
y = sin(x - 1)*pow((x - 1), 0.5)*cos(2*(x - 1))*sin(0.5*(x - 1))*cos(x - 1)*sin(2*(x - 1))*pow(cos(x-1), -1);
}