Copy and compare the iOS clock animation of the elder brother

Source: Internet
Author: User

First, preface

  Before looking at a variety of colorful UI effects animation code, the method is to run an article first, and then go directly to the implementation code. When learning to embrace the attitude of viewing, to know, is not wrong. However, after understanding the pixel, animation rendering mechanism, coreanimation API, derivation of two-dimensional, three-dimensional affine matrix, we can change the Reading UI animation blog post or the way the source code.

Talk is cheap, show me the Code--linus Torvalds.

A large amount of imitation writing, must write more--ye isolated city __ on the Codereview line of speech at the General Assembly.

Recently, the home, APE, Mushroom Street, drip are talking about iOS client architecture design, a lot of children's shoes in said can not understand or is Viper, is not juchongruoqing dare to comment easily. But only through the cooperation of many people, there is no unified architecture specification, constantly fill viewcontroller, so that the VC from dozens of lines to thousands of rows and then split to hundreds of rows; experienced nearly hundred VC class of various products jump demand (blind) new (engage), to understand massive Viewcontroller Pain and Page jump logic cyclomatic complexity is unbearable.

Comparison of the result of the UI animation of The Imitation writing

  Original link: http://www.henishuo.com/clock-animation/

Engineering operations provided by the standard Cobovin The author's project operation

  From the visual perception of rendering effect, the quality is similar;

From the UI aesthetic point of view, the main focus on the core functional coding, I have some attention to the meaningless aesthetic appearance, so the pointer and the Jong Center of the pointer cover to make a path to draw, it will look beautiful ^ ^

From the operational performance point of view, CPU consumption is 0, memory, animation fluency and other aspects are similar

From the point of view of the component usability, the brother of course should not waste energy to do such a simple component, so I provide the component API is more, provide code XIB compatible initialization, clock time setting, pause, run, clock time value of manual kvo, dial background map settings, etc., basically there is the need for virtual clocks , this component of mine can be used directly.

From the point of view of coding, the elder brother transforms the real-world problem directly to the machine essence, for example directly specifies the duration of the pointer animation; My component development mindset has been to build the middle bridge between the real world and the machine world, so that any real-world law can be transformed from intermediate bridges to engineering methods and UI displays. Any running state can be mapped to the real world through an intermediate bridge, which is understood by human logic. The idea of brother-in-the-mark is certainly efficient, but my ideas are closer to human thinking. Or that sentence, the way of programming is not fixed, but by your own choice.

Third, UI and technical requirements analysis

 All the requirements analysis and coding work is to read the code provided by the source demo before, in order to exercise individual independent analysis of problems, solve the problem of ability.

UI implementation, because does not provide the interaction, so choose the lightweight calayer, the use of the OC class is mainly UIView, Cashapelayer, Uibezierpath. In addition, I used the cagradientlayer on the drawing of the center cap.

Logic implementation, my idea is the cycle of a second after the man to drive the clock time property changes and UI updates, so the use of Nstimer. Here Nstimer has a strong reference to the problem, there are four basic solutions: weak references, associated objects, intermediary agents, GCD timer and so on. The elder brother chooses the first kind, my view is that I need to be strong to hold the thing which I want to use, certainly this also is from the philosophical speculation to consider. Therefore, I used the intermediary agent of this method, has been written before, directly to use. In the implementation of KVO, I used manual kvo, because the time property provides the user with the setter method to set the change, the access party certainly does not want to observe their own settings when the KVO, you have to remove, and then add. Therefore, when I encode the setter method, I do not publish the change information, but instead provide manual kvo when the clock automatically runs.

It is important to note that the creation and submission of Nstimer consumes the CPU, so do not create the destruction frequently and replace the timer only when the access setting changes the current time.

Iv. Class design and coding

  In other languages, there is the concept of an interface but OC does not. So how to interface-oriented programming, I think protocol is a desirable method. Before writing a class, if there is time to do the interface design is better. Examples are as follows:

@protocolHsclockviewprotocol <NSObject>/** a clock communicates with the outside world, which is its time. * To have setter/getter, Kvo-compliance*/@property (nonatomic, assign) nstimeinterval time;/** * Pause clock operation*/- (void) pause;/** * Continue or start clock operation*/- (void) work;/** * Set dial background * * @param image dial background, UIImage object*/- (void) Setdialbackgroundimage: (UIImage *) image;@end

V. The transformation relationship between the real world and the machine world

In the virtual clock this problem is still relatively simple, mainly in the time string or Unix timestamp to three pointers to the radian angle line vector conversion, the code is as follows:

/** * Angular angle of hour, minute and seconds (z-axis outward)*/typedefstructHsclockhandradian {DoubleHourradian; DoubleMinuteradian; DoubleSecondradian;} Hsclockhandradian; Hsclockhandradian Hsradianfromtimeinterval (nstimeinterval time) { time+=8* -* -;//Beijing Time +8Nsinteger Offsetin12hour = (nsinteger) Time% ( A* -* -);//in the 12-hour period, the number of seconds to offset , the hourNsinteger Offsetin1hour = (nsinteger) Time% (1* -* -);//in the 1-hour period, the number of seconds to offset , the minute handNsinteger Offsetin1minute = (nsinteger) Time% (1* -);//number of seconds to offset at 1-minute intervals , secondsHsclockhandradian Handradian; Handradian.hourradian= Offsetin12hour *1.0/ ( A* -* -) * M_PI *2-m_pi_2; Handradian.minuteradian= Offsetin1hour *1.0/ (1* -* -) * M_PI *2-m_pi_2; Handradian.secondradian= Offsetin1minute *1.0/ (1* -) * M_PI *2-m_pi_2; returnHandradian;} Hsclockhandradian Hstimefromtimestr (NSString*timestr) {NSDateFormatter*dateformatter =[[NSDateFormatter alloc] init]; Dateformatter.dateformat=@"YYYY-MM-DD Hh:mm:ss"; NSString*DATESTR = [NSString stringWithFormat:@"1970-01-01%@", Timestr]; NSDate*date =[Dateformatter Datefromstring:datestr]; Nstimeinterval TimeStamp=[Date timeIntervalSince1970]; returnHsradianfromtimeinterval (timeStamp);} Hsclockhandradian hstimefromdate (NSDate*date) {Nstimeinterval TimeStamp=[Date timeIntervalSince1970]; returnHsradianfromtimeinterval (TimeStamp);}

The transformation of the angle of the pointer radian to the affine matrix

The author suggests that the conversion relationship should be deduced, so it is not intended to provide a conversion matrix ^ ^. Two-dimensional translation, transformation, plane origin rotation, plane any point rotation, three-dimensional translation, transformation, rotation around the axis, rotation around any axis.

Here are a few ideas and points to note:

1.cor_new = Cor_old * M, where cor_new, cor_old are line vectors, one is the original value, the other is the expectation, these two we know, we can deduce the affine matrix M.

2.iOS uses the same left-handed coordinate system in the CA as the Uikit, while the three-dimensional coordinate system is z-axis outward. When the two-dimensional rotation is counterclockwise, three-dimensional angle to the negative direction of rotation axis, counter-clockwise for the direction of growth of the rotation angle.

3. When rotating around any axis, the coordinate system is converted first, so that the axis of rotation is coincident with an axis, after which the coordinate system is rotated, and then the coordinate system is reversed.

4. The derivation process involves matrix operations, multiplication, inversion, etc., involving trigonometric functions and differential product.

Vii. private properties, member variables, and private methods declared in the project

About writing a private attribute in the extension or in the curly braces after the implement to write the member variables, Tang qiao great God has discussed, interested can go to see the Tang Qiao technology blog. Whether the private method is declared in the extension, my view is to write as far as possible, when others look at your code, you can quickly know what private methods you have implemented. The code examples are as follows:

@interfaceHsclockview ()/** * Internal ID clock is in operation*/@property (nonatomic, assign, Getter=isworking) BOOL working;/** * Initialize current time, background, pointers, for code creation with Xib create shared*/- (void) P_initclockview;/** * Initialize pointer and return * * @param width pointer width * @param height pointer height * @param taillength pointer trailing length * @param ticklength finger Tip Length * * @return Initialization of the Shapelayer path*/-(Cashapelayer *) P_handlayerwithwidth: (cgfloat) Width height: (cgfloat) Height taillength: (cgfloat) taillength ticklength: ( CGFloat) Ticklength;/** * does not include the clock run identification and modification of the private method, animation execution and UI Update Main method * * @param time stamp to be set*/- (void) P_settime: (nstimeinterval) time;/** * Timer trigger processing, update clock time*/- (void) P_handletimesource;@end@implementationHsclockview {Cashapelayer*_hourlayer; Cashapelayer*_minutelayer; Cashapelayer*_secondlayer; Nstimer*_timer;}

Viii. Conclusion

  This project has been written for almost 5 hours, the coding speed has yet to be improved, in the coding thinking, re-thinking is to build a real world bridge, or directly into the machine thinking, or the two good comprehensive use.

The project source of this article: Https://github.com/1962449521/OCDemos/tree/master/ClockDemo

Copy and compare the iOS clock animation of the elder brother

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.