简体   繁体   中英

NStimer and setNeedsDisplay

i have some problem with nstimer and ui update and drawrect, I have a viewcontroller and put a timer inside, it runs every 0.02 secs, in this timer tick function, I make an imageview move from top to bottom( change centre of view), then add another view on, and when touch begin touchmove and touchend on this view, draw a line and call setneedsdisplay, when my fingure moves on the view, the imageview i mentioned before, moves slower, by checking the time tick, I found that, without finger on, it ticks 0.02 secs, but when move on, it slows to abt 0.1 sec, which make the imageview move slower, any other way to optimise it, I think the setneedsdisplay did the thick, ofcourse, I try to change the runloop mode with

      [[NSRunLoop currentRunLoop] addTimer:tickTimer forMode:NSDefaultRunLoopMode];

not help. pls help, and another question is will another thread help this? I tried nsthread, seems not help.... lol

For this purpose a much better solution is a CADisplayLink , that calls a method each time a frame is going to be refreshed. That way you'll avoid desynchronization between the timer and the actual framerate.

You set up a display link eg like this:

_dl = [CADisplayLink displayLinkWithTarget: self selector:@selector(refreshFrame)];
[_dl addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[_dl setPaused:NO];

and in the refreshFrame callback you can update the screen. You can make use of the duration and frameInterval to calculate the time that passed from the last refresh and adjust the movement speed accordingly:

-(void) refreshFrame
{
    CGFloat speed = 10.0; //points per second
    CGFloat timePassed = (_dl.duration * _dl.frameInterval)];

    //refresh the view (example)
    CGPoint imageCenter = self.imageView.center;
    imageCenter y += speed * timePassed;
    self.imageView.center = imageCenter;
}

This way the speed of the view stays constant even as the framerate changes in time.

It is wrong to assume the timer event is going to be called with exact intervals. Calculate the new parameters based on the speed and velocity vectors and time from the last update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM