Using Quartz to draw every second via NSTimer (iPhone)

跟風遠走 提交于 2019-12-11 13:35:52

问题


I'm relatively new to Objective-C + Quartz and am running into what is probably a very simple issue. I have a custom UIView sub class which I am using to draw simple rectangles via Quartz. However I am trying to hook up an NSTimer so that it draws a new object every second, the below code will draw the first rectangle but will never draw again. The function is being called (the NSLog is run) but nothing is draw.

Code:

- (void)drawRect:(CGRect)rect {
    context = UIGraphicsGetCurrentContext();

    [self step:self];
    [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(2) target:self selector:@selector(step:) userInfo:nil repeats:TRUE];

}

- (void) step:(id) sender {
    static double trans = 0.5f;

    CGContextSetRGBFillColor(context, 1, 0, 0, trans);
    CGContextAddRect(context, CGRectMake(10, 10, 10, 10));
    CGContextFillPath(context);

    NSLog(@"Trans: %f", trans);

    trans += 0.01;
}

context is in my interface file as:

CGContextRef context;

Any help will be greatly appreciated!


回答1:


Your example won't work. The reason is that drawRect: is called for you when the view requires drawing, and it can't draw on its own.

Instead, try using your timer from outside of drawRect: (viewDidLoad comes to mind), and each time add an object to draw to a list, and call [view setNeedsDisplay] to request it to be redrawn. There are other techniques if you need stricter control, but it's a good idea to master the basics of application flow first.



来源:https://stackoverflow.com/questions/2609306/using-quartz-to-draw-every-second-via-nstimer-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!