Paper tail-Quartz2D-timer CADisplayLink snow effect, cadisplaylink
Timer CADisplayLink snow Effect
1. The overall idea of timer Snowflake:
First, draw a snowflake on the Controller View.
After the View is loaded, add a timer.
Call the paint method in the timer method.
In the plotting method, modify the Y value of the snowflake.
When the Y value of snowflake exceeds the screen height, set the Y value of snowflake to 0 again, starting from the top.
2. Add a timer Implementation Scheme
First, NSTime
Second, CADisplayLink
Finally, the CADisplayLink solution is adopted.
2.1 Why not use NSTime for CADisplayLink?
First, you must understand setNeedsDisplay.
The underlying layer of setNeedsDisplay will call the DrawRect Method for re-painting.
However, it does not immediately re-paint. It only sets a re-paint flag and will call the DrawRect method only when the next screen is refreshed.
If NSTime is used, it is assumed that the screen is Refresh once every 0.01 seconds. In the middle, it will wait 0.02 seconds.
That is to say, every time we wait for 0.01 seconds to accumulate, the change will get stuck.
When CADisplayLink is used, its timer method is called every time the screen is refreshed (usually 60 times a second)
It exactly matches the time when setNeedsDisplay calls the DrawRect method. There is no waiting interval and no screen freezing.
2.2 how to use CADisplayLink to add a timer?
Target: the object to listen.
Selector: Method Name of the listener.
CADisplayLink * link = [CADisplayLink displayLinkWithTarget: self
Selector: @ selector (setNeedsDisplay)];
To make CADisplayLink work, you must add it to the main running loop.
As long as it is added to the main running cycle, it has nothing to do with the Mode
[Link addToRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode];
3. The specific implementation code is as follows:
1-(void) callback {2 CADisplayLink * link = [CADisplayLink displayLinkWithTarget: self selector: @ selector (setNeedsDisplay)]; 3 [link addToRunLoop: [nsunloop mainRunLoop] forMode: Unknown]; 4 5} 6 7 8-(void) drawRect :( CGRect) rect {9 if (_ snowY> rect. size. height) {10 _ snowY = 0; 11} 12 UIImage * image = [UIImage imageNamed: @ "Snowflake"]; 13 [image drawAtPoint: CGPointMake (0, _ snowY)]; 14 _ snowY + = 10; 15}