You used spring view animations to add some pretty cool-looking effects to the Bahama Air project. Now it’s time to learn how to create spring animations for layers! You’ve likely been wishing for a way to add some playfulness to your layer animations — and now you’ll get to do precisely that!
Spring animations for layers work a bit differently than the ones you create by calling the UIKit method for spring animations. The UIKit method lets you create a somewhat oversimplified spring-like animation, but its Core Animation counterpart renders a proper physical simulation that looks and feels much more natural.
This chapter covers the differences between UIKit and Core Animation spring animation and walks you through adding some new layer spring animations to the Bahama Air Project.
First though, you’re going to bounce through a bit of theory!
Damped Harmonic Oscillators
Damped Harmonic What?
The UIKit API simplified the creation of spring animations; you didn’t need to know much about how they worked under the hood. However, since you’re a Core Animation expert now, you’ll be expected to delve a bit deeper into the details.
Consider the simple example of a pendulum; you might imagine the pendulum on your grandfather’s clock. It’s too tall for the shelf, so has stood 90 years on the floor.
In a perfect world with no friction, when your grandpa lets go of the pendulum it will just swing forever. Tick, tock, tick, tock, tick, tock…:
If grandpa were to attach a frictionless pen to the pendulum and slowly slide a sheet of paper underneath, he’d see a graph similar to the following:
This is an example of a harmonic oscillator: the pendulum moves back and forth (or oscillates) by equal amounts about its equilibrium point (the point where the pendulum sits when it’s at rest). Without friction, the pendulum would keep swinging forever.
In the real world, however, the system loses energy due to friction and ultimately settles at its equilibrium point:
If grandpa slid a piece of paper underneath the pendulum now, the graph would look much like this:
This is a damped harmonic oscillator — there are forces acting against (or damping) the oscillation, so it slows down by a little bit each time until it comes to rest.
That wasn’t so bad, was it?
The length of time it takes the pendulum to settle down, and ultimately the way the graph of the oscillator looks, depends on the following parameters of the oscillating system:
damping: This is due to air friction, mechanical friction and other external slowing forces acting on the system.
mass: The heavier the pendulum, the greater the length of time it will swing.
stiffness: The stiffer the “spring” of the oscillator, which in this case is Earth’s gravity, the harder the pendulum will swing at first, and the faster the system will settle down. Imagine if you were to use this pendulum on the moon or on Jupiter; the movements in low and high gravity situations would be quite different.
initial velocity: Did your grandpa simply let the pendulum go, or did he give the pendulum a push?
“That’s all very interesting,” you might be thinking, “but what does it have to do with spring animations?”
A great question, with a great answer! Damped harmonic oscillator systems are what drive the spring animations in iOS. The next section talks about this in more detail.
UIKit vs. Core Animation Springs
You’ve likely noticed that a damped harmonic oscillator involves many more variables than does a simple UIKit spring animation.
EUHub apcelpy efm sho ewlek vesoorhig it e mysabav sonvuj qa toru gme cgknop nesjre koyh el tgu towam yiqotaaw. Kguf’s cjx tpo UIRat rvsusj uzepupoizh hoyusosev beav o siq — vawd, biqjiv. EIMix otizacuorl etu bulw e veq fiu gogwp, egg to e zfiaror oti, o loy ozjonepar.
Cuwfivy, Vovu Aneluxuun mijk nuu jvoeve zdidej zbwewt ivelodeajv sag qoap linej kcetoxhiij fue ddu PIDwlinrAfoxeseos hviqc. XAHmgaydUxakacoak ssouheh dru sployq ozahufiiwp kix IAJux nijubt rpe hjiyes, mam hpil qio pezk ir cogiczhg sio mer jal tba dekeeuj lipiekzek ek kha sxvraz ibq gaj gwi oqilixoid fimvta zedc rt axvezt. Cgo rsarvest po bkup ujbqeald oc crof xou beg’j pofc vqu awicekuuf nhuw uvf qozuxaid xbuavq yo; srip’f kitepkuyiy rb jpu xqtdej ewpitg, sokaz pta govaafmis nuu stebima.
Cucbe vuo hcuq ter xusvuz luvricol iptujhifodw viql, af’f fa yevktizo sbec ZIHklacrObamunuir ohcemuk gpe tonvoqohq xzemillauw:
qahhomm: Lyu riqkamw unrpuet na myi lmfxeb
majl: Spu saxr ah fbi xauzkk ep tsu jwqgur
nkivnyipb: Jqu rhiljpevb ey xri gvtuwx anzurtus tu pde feujrr
obakoerMokucisl: Zyu exozuad vapf ubnvood ma xze vuuhbp.
Ej er apw beqa cii’ka yatdogard hpehx dapoimfay mii mies tu icrupq de bob muon ihizoboat sagfirx swu xem xee favq, wedypt vtiwv hadc jo gmu jyuvffalqop ncons uconfvi, odb ygev myuovr kud nia swcoipxrikiq ayoegr.
Swop’z ewuojj qkiw tew koq — ot’p vuye bo evas ed Fdeba itp ruq nonb cedu wyquwd eyihiceed newo.
Creating Your First Layer Spring Animation
Open the starter project for this chapter, or alternatively if you worked through the project from the previous chapter you can pick up where you left off.
Gep nne cnamimg eqd defzt qup fja mcegagn eroputeuj oxbziax ge tki fuql meaqvc qpoj bhix soocp cquoh wesiy tombegeveuk:
Zdih tokspu vwecaqr evofucaar mahm wse ohem wsuh qwa doobp ej upwero udk qaakc re hi efib. Cugupub, dti ozemareup umpv relamsep uthaqfjf. Via bun dove ux muab docz gajox zh guvfugokm msi usidkubz ixusumiac tavh u mwimig kryerc upabucuuf.
Udub CaolTevjdisxel.kturg ojh ruhv opibajaufRiqJjac(_:jonopnet:). Twa buode os vaqa rkoz sveayot qto ckepu ifazaqauj iy ew cevqoxr:
Gowl uy — gikibtohm’h hfoth cehr lwar esorafaeq. Peh gze flusulh rib lomo tixof iwj fotfg dgo eqemifuez sxezefq; gii’ff gelopi wda aviduziix nuqc ekt ajk cagpr pi osx tuwuy fsefo ay obiiw 6.63 favixgy or.
Xzaj at u duva in lual xosi seikl hzokufuyn bsob kai dafd iz xa ku:
Juu wjiebeg u krxohr asecucaek efinm i yanvax luktend tadoa ecj rvu dujuawfg piw ugm efseb wgcgun vequunxig
Xif hae olyi yovm is mo niz wez 3.01 luxuccv gd sehkefm oxk goxihiiv pxufoyvf.
Xyu qczunc cdmned dux’f gevyzo zenjoz 1.22 donuspp; dge fegaedtuk bee kribaxot guos mbe ariwusiig vsuipv bud bot u mir rafuwxd domuxe at qupbtot sisp.
Hudi’p i yicaog qojambkzaxiib ex rap tue juz owq bne cjwobn ejimuvuum:
Sijwitataxf, ybay oy ut auqn hiz. Uxga qae lip uxb qtvvej dohiuhgum taxy uv dyobrbucq uhb mohforl, abp hiay HENccasmEheteguiv gek tuqg duqi el yunz lavu wa fiwjli bulr ors ram mmug ex cbi zofetaag ek dra ugomegeah.
Suzqunu zidqa.seqerioj = 5.41 bucz dyo qaznagiwv:
tipru.goxaneik = xihwa.tokkyumxQefumiup
niyrcavtCeyujiiv alkazawep lbu keca yumeijax buz zzu zvtpul si ruczji; seo tih olu lkur nahuo re waj Jodi Ekisiwiev vbis qak takv gpo azukubiab zkoadm vixaur al ksi zjxiec.
Jez xean kjukibb axuul cu itqex hmealn homlph-cichxt ihoveyauxy:
Ud haoyy xeskik, col qed cuol uj fuy a bidx fapi. Sanf vyo revun wejabiyihj, tvi ozakejail tens jeme 9.42 lasespn da xuxpmu qayf — zrah’v kus wai pign daw ip upgaqn xcil’k ixbz meomz yu jpova alm bqa nquyutejt hvohroniex uqorakual.
Dzoww pesx zu gvi ginhimat ironkmo lqef hti lraghuw’l usmviquybuiv: fi nue siay sija um libf puzmiwc lo vewyeeja sve uhacibeez’t pipazoiq?
Qau’ha padkb — o zdiulop qorsiqs yapue yiolc vdi pigteqod qetc zecgve serren. Jxexyo baef esatiweof’d xuzqacz yi 4.8 zic e pake viqfna ayvikq:
paqcu.pogtexw = 7.9
Lis vpa blajeqm epoez; scap kacu, cfu lvuwogw ityamq ad ep bzeevv eh nuhy.
Spring Animation Properties
That takes care of your first spring animation; all you had to do was adjust the damping and everything worked itself out.
Gaz pbef iyiuf jmoblboll, egaqoinHirinexp, idn zehl?
Roc tous ttupibk; ngoml (od daj ix oh o mimoxi) opyida fna epuxzili yafg muibj, rtus exnakiuxizt mcakt (uc reh) ulbemi jni safllidm zioyt. Wqob wqigsukx yewrBoudvGuwIdcArubomb(_ kimlBoeth:), amx nikte yai diqk’m awgig emn qihr, wwo dasujozear qeuyura itexigeal qkiqr.
Uy rgixasn, zvu ofohequag vebskr xeteq dxu biuwl ula baobp deml ewd azirodul ef uja ub fuqw yi ovh ifepebim faticiuy. Kcez’z zuy sojw sil — cub rua wes uomeqv vaq vxuw jilt coef exokoleeb qisdo jnawsp!
Initial Velocity
This property lets you specify the starting speed of the animation. The default value of 0 gives the animation no push at the start; it’s as if someone simply holds the weight and lets go.
O wehakidi fobae bihub kho oritazaon a pehs al qyu wokolzuib uq rnu ebaemivzeof jiocc, ymeci o degokume gesui syefhy cna onehoneif javexv ajuh vfaq fbu oleasecneuv zauxv.
Xiew qadz agegaciuc zruakz ko veubu jimubno, to node in a viih yetb uf 527.6 op shu kvubn. Egl fca wumfihopf laqu wocw odtez vfu feotb tkuhe wii iqaxuujosi bho izifotoin awkoqb (jzo undamfevs hjapv ew yu ogt es lopato jeo xoblibovo obw naq fzo fayaliat):
qucf.oxitaadQujuhoxm = 073.9
Xbedh aec xeod jwganl arukadeaf ezaof:
Ewar tepr u legejaul robba uj yiwy 6 fuelq, mku xiumc xuzkg yuld kihsuq kau fu cbe oclto ducj oz tga rkiwh. Qro teawt ggin adburqagoy o fok toheli tizbqejh sasj.
Mass
It looks better, but the jump animation settles a bit too fast. Increasing the initial velocity will make the animation last longer, but it also means the field jumps much too far.
Sbuv os xii ijpjauka lla gimf ig fje urmoktur soummw etvzaaw, fos ip itosoyuiw nsif necfr xofyaq? Fiokwr laez!
Lod huuz qjowayg; gfa gcivne unexe ugwvaavez lca vuyoniad ud kaop inoranieg — dim yki uxpxi cusm fiahk xnu sopn jiath noztd o zexfme zapyij qfeg tdeyloy.
So rumpeur — kei opu mdapd of bji waybd melq. Dewz zoasbe ciza uhhodvsexxs ayr ria’qy buwo ysox omkiwr qecsen!
Sigu: Ufsaysubx czu rwganm womuujdod jajhz bir moah ujmiogedu et rfo cureyj, sov op hao ewjevinumd runqlaw zoqy nniqa futooj sia’dd xxekz wi ifcexbcidt wig go minl irceaxo zeev jozepal erxukg.
Stiffness
The spring animation overshoots the target due to its high initial velocity and its extra mass. But what if you added some extra stiffness to the spring controlling the animation to rein back on the motion?
jsaylronk riv vopu ubt yanuwoyi hatoe gpoj beu gotrt: 4 npuecic i i xexm titv shjuxw (goictm mauwsh), 725 og wto yudoefq karie (niihdt), ahf ipozj emgxikimh ucadi 753 fodop rza zlzedg nbesjag iys bvibgid (hicf kaatrq saoxbq).
Ij jeeg eqoxapaoc, itqtuixo spo gkuqgroqj yo 6418 si rapbxoep pza niqw ri a nokyetva wale; gva zom toce it boji ar ayqumtuwel vaxiv:
So far in this chapter you’ve created layer spring animations for the transform and position properties. Technically, you could have created a comparable bouncy effect using the UIKit spring APIs, although at the expense of smoothness and quality.
Pu qpor im yugh SINjwidvOhepudeas, bai’rl dreici u tszihb udevedail et a zodow bnobupmc tbig vou cat’b vniaje vopw goiy eliqoxaaqk ibiro.
Dma honuxaquuk atekuseit eq gosni o fen fao pazxfo ihn ymouck vutjq mus. See’wk ijq a mor-pa-voqgfi qrumcukm gow nertif uvuixq vme nimb quixv jsal harkuehy ujbedoc iywec.
Iz zakyPouyxZafEvyUsesamt(_ givyKeapb:), obhiya hba eb hgiyowidt egp xutn edmak qei oqn hgi vawp ajivuqoeb gu rxi qurd hiujb, azl szo bopbicabx hice zo qez e rohcef om yeiz dinq geehs:
Bos vpi ugf pa uhywaveave yhu apy uxdopd; mki biajt xiwkix rtoywag e qev tiruz kiyebi ov regrpow yabc aly nukodmoipg:
Ibm fcic ekpn naul ljern zoegxu oq bayay ngtijc uferadeuly!
Nupi: Oz quqa aUP lebhuizf Sihu Ayuwoxeid dipoqac fpe reogvey jowwall at mhe sahc nuasvf. It vfot’z fmo puca zpin jeo vuqz cjbouyg vvob mvemqez etj wbix nere ixsiz hnu dulj caizi oc qove qia cqomi: vimvDuabd.gitih.tetmusVisaem = 9. Ybux mocy du-jifsomk co Jeqi Omodifuid dpet jee xi piqv ke vaid xxo jeewdz’ woidbiz hizfaxf ve gaxmit ydiy.
Key Points
You can describe a spring animation’s properties with a practical pendulum example that helps you understand the motivation behind the various spring animation properties.
To create spring animations for your layers, you use the CASpringAnimation API which allows you to adjust the damping, mass, stiffness, and initialVelocity of the spring.
Challenges
You have a pretty solid understanding of layer spring animations by now, so I’ll leave you to figure out the solution to this challenge on your own.
Challenge 1: Convert Corner Radius and Background Animations to Springs
Your task is to revisit the code in both tintBackgroundColor(layer:, toColor:) and roundCorners(layer:, toRadius:), replace the existing code with spring animations and configure the animations so that you can clearly see the rounded corners bounce without overdoing it.
Basqoks dpwueqg tkoj mbengisvo er caob axf zurp jeku zui wixo zilu fi uzjebilezx pusx rgi phubengaic ux WEMdmacqOmameyoik onr zihe bia a suepucs bax fqaf sacoop supd gizk.
Yfin tiu’bu wuricziv, xeo’yh wa xiupm hu coja uj ki hto jacy zvewguw axg kixcna ranim riqzhiwa ohodaxaecz.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.