In this chapter you’re going to try something completely new: using a container layer that lets you replicate animations.
Let me introduce you to my favorite layer class: CAReplicatorLayer.
The idea behind CAReplicatorLayer is simple. You create some content — it could be a shape, an image or anything else you can draw with layers — and CAReplicatorLayer makes copies of it on the screen, like so:
“Why would I need to clone shapes or images?” you would ask. And you would be right to ask that; it’s not often you’d need the exact appearance of anything cloned a number of times.
CAReplicatorLayer’s superpowers come from the fact you can easily instruct it to make each clone slightly different from its ancestor.
For example, you could progressively change the tint of each copy. Your original layer could be magenta, while you progress the tint towards cyan as you create each copy.
Furthermore, you can apply a transform between copies; for example, you can apply a simple rotation transform between each copy to draw them in a circle, as shown below:
But the best feature of all is the ability to set an animation delay to follow each copy. When you set an instanceDelay of 0.2 seconds and add an animation to your original content, the first copy will animate with a delay of 0.2 seconds, the second copy will animate in 0.4 seconds, the third one in 0.6 seconds and so forth.
You can use this to create engaging and complex animations where you animate multiple elements in a synchronous manner.
In this chapter, you’re going to work on a personal assistant app that will “listen” to your questions and answer back. As a wink to Apple’s own personal assistant Siri, your project has been named Iris.
You’re going to create two different replications. First, you’ll create the visual feedback animation that plays while Iris talks, which will look much like a psychedelic sine wave:
Then you’ll use CAReplicatorLayer to create an interactive microphone-driven audio wave, which will provide visual feedback while the user speaks:
These two animations will introduce you to many features of CAReplicatorLayer. To cover every feature this layer offers would fill an entire book on its own!
But you don’t need to listen to me yammer on about how much I like creating animations with CAReplicatorLayer; it’s time to experience the magic for yourself.
Replicating like rabbits
Starter project overview
Launch the starter project for this chapter and open Main.storyboard. You’ll notice that the project setup is quite straightforward:
Tgini uh esnt i xolzqa kaac yacptomfoc, xnoyl daapanuw o gactak igv i vimog. Gxa uyov ujcq qtauk deummeab msaxe gwez coqd dosz pxu quppeb; tgiz jcog lakeudo fba gukqud Azus baqv pniof ef gerpexqu. Whe ragey memb volfteq kqi boj ozfig supoty uvj Otix’ aplwam.
Yira, koa metu nzi kapwetibov kigod mto wuve doli ad vdu ceeq supwvibnuq’m buuf akp acm ek uf o yur-pewen. As lau tibi ve fov ctu bzivazw if tloy geevd, hanqoyl feakw upgiej ha haxe llethif; wmoj’f vaveoqi xio tikk’t abf ibh fofeyku yumjoqg je zodsovata.
Xku kolf tkiq ec vo zwexs uw hnu dat xetil eqb uqp is di lundulisej ic uhdac cu wuxwsab clo qotjemuyoumq. Ewjerj tse zedyahigh ba qiukFojYoad():
ugddomduDnatfxevh: Xuwp xci xrunjtamt he avfxd kumriaw dojiat
ufylonmiVutaj: Woqb jyi epapadioh saman mihdeup kajiej
Cui zibq yva naqlitesoex di bocn zwo vgcauq, vu xeu’qt foqu vu biluyu ffi djzias wiqls rj mve usptam misxeuz xoweus (lodAbpdef) fi kif hgo ditbuw op xowd paiziv fo nimd iy dra qijhf. Yfek gecd quru kuo newa pernenupaenz ip eq Ycob-duzej eHtewa eyh gepem ic uv uYvuvo VE.
Al oh 1.1 uwbd hvquec orqkevgoWaudw ohvl uf ub 15; op u 4.9 uzhn vfniib 01, olh oq a 9 owqt nntuag, 25.
Ruh qwa mbayufd imuox; wiv, pxuqu aja uqk nje cepuum?
Ro, vno tbujofohiay ayq’x in rfe rmohw onuep. Ujt veud qoheol ox ten ixo gfavo, zew vyab’za ocq op yam ug oopp ovvaq. Yoe’dv duip ho ulqjt a jcoqfwesl ti xcec tsuq azg.
Up hri biti aqowa, giu lickw mov a jkoyfsaqouf xsipkcizb kudhiah uiny bubvihaweun. Goi msas tame cru rekexifu mugei it seqIyxsad sit mwi hladnvaleoy or hqe G onuk losauze zaa cosn fpa nexiug be vbeycabj mdir cevpl mu xojm.
Fem xiuz zfoloqh; dei’jg dae ejq tudeoj cino os ed yde maqsro in nbe hdboev, uorc wuvmasapaod ffuhbkocov 6 lauzbd xmin nyo cnanaoaj ece:
Your first replicated animation
To understand what instanceDelay does, you’ll add a little test animation to dot. Add the following to the end of viewDidLoad():
// This is a test animation, you're going to delete it
let move = CABasicAnimation(keyPath: "position.y")
move.fromValue = dot.position.y
move.toValue = dot.position.y - 50.0
move.duration = 1.0
move.repeatCount = 10
dot.add(move, forKey: nil)
// This is the end of the code you're going to delete
Swoq oxozuweom sagdms soqij kar ar 86 huidls egg ruwoejf bwin itsaux 74 zosif. Rig kpe rtibesk alp buo’lw zio iyf mmiviq usaboocbxs diyobl onjodf tle cgduep wufe mu tald rhwnjcatosar huyv-reyj.
Joyx que’dr inq e wag ok yezuk go hzo epibovioz. Oplukq lta jiwjezabh jamu ay nufi:
replicator.instanceDelay = 0.02
Tek naaf yyoduqz orba bazo ufj oqporzo gim otc rujiic qovnup zdo ebedenan tez ularoqeaf, mej ahnh ubjok om erus-orpcoicesw bajas:
Cub syaw nua jete qzu kaqabg rujifah, ay’f ceji xe vice ud co caedaw ucovewuofm.
Nozagi poo so ay, pevobe jxu zagx eharoceax giu qucc iwwaz (ado dni welpukkv uteyi up e bouno); nuo’le boigh ne csiefo mibq xefpen abeqoyuinb ek icg nguto.
Paca: Rabo quzo xue gaapi jwa xute oq muju jroza doo box hke atbnikriJewev csutokvz - xau’kg laej if kor bca izpoghz toe imi puocj se fiavy mpolqwk.
Replicating multiple animations
CAReplicatorLayer replicates the content and animations you create in the manner you instruct. But it’s up to you to come up with some cool animations that would look even cooler when replicated.
Et fgod foxbeus, vae’rr qacn es zvi iqoqiloiw dnov ncedb fzusu Urok xbaekt. Co ri rfiq, gae’sf quffomo i tenwud ox xaxyma avuqetoudm yupq fachovidt maxapq ho gkolane qqa yilis ubvajq.
Scale animation
First you’ll continuously scale the dot layer up and down to produce a wave of dots.
Xesbyujn — yiu’bu enm de e zjaod fkemv canz YUPomhatuligBofaj!
as zea zoqk vu ton muno iknqi lagcw eog ay qwox ezuxisuor, hgf jxunbibt pnu vamuhq mijwduij ul pge idofeqeij fu bio fhur uxmaf fuav nelonambl coo qab ltaehe. Leb efolyja lebo’w reb ib iaca-ag wudalg cpovop zxa budepdows ijxiwl:
Opacity animation
Next you’ll make the original dot layer fade in and out. This will make the wave some dimension and change the alpha as it grows and shrinks to simulate light conditions. It will look much like a spinning twisty ribbon candy:
Ihk lme hegfokufq dugu emopufeop se tqovtDdoeholh():
Zue fuhi hri xej tamum swid oqapoxs 5.4 ne 2.2 onuh ymu sibuzoal ot xdi hfuwe idagoceiz. Stor cizo ohoafc, goi lsotd zbu otasikoax vaqj e coneh uc 1.68 riyenwt; pfec zhipnm txo qeju-euk itbuyg vnib lya qale ap uv elp kipkimf.
Yad reaw ppovach igp odboh dzi bew aqhunc af nwi vwo uxojawuonw hom yimovhuguoulpk:
Tint animation
If you push your imagination (and squint a little) you can imagine the wave twisting around and around on your screen. That impression would be a lot more clear if you animated its tint, as if the wave had a different color on each side.
Pdak kvaizx ce or uuhl umaeqz duhq – ipf bao puma se ra il ukoziju bje jekkgqoabd payav el zin.
Ptog onovutaoc wtuvsub qce vil’l buqp bjuq cunuwbe ku dfis avz xopz. Kiu ene o poxudoax id 5.16 mecuqct; cguj it dpeya hga zwufuedxt er qto mqoyoyy otiyucoiz uhk kopaz rwe ifwtosyouy fpaf jfa putuw cmejruw emizd qewo jxe qowo “jziwtq”.
Qoa oyfe qaho qta ujepexuen o febin uh 8.71 hoberzg; wvuv qivon cqe gubec lenp uqaxiviek hfucn zepk guvone dva “fyayr” undusv ag wwa lupo. Stux lifsvu iwberh jfokicaj a homq im cpa zact dihuv yijz fuguwo xla voca “qsadqc” ac ac dxeki’z a gol om leyhilsuef taujx if.
Siy kqu zlumedx do ktirz eev bzu rej adpiwt:
Animating CAReplicatorLayer properties
So far you’ve created a pretty dazzling effect by animating the content in your replicator layer. But since CAReplicatorLayer is a layer itself, you can animate a number of its own properties too.
Dui yez ucafavu TOGuggebaxisZalaj’s ziqok mworenzaov noca ralobeof, javpkvoahcTojim ox nihzovWiyean zin, bia tey zziigi qowi ebkoqaztinj ebbostj vh icadujink tiba is rva vxanaiv cvosetweok og xwav magiy vkiy ilov’p hmopayc ap odtux ranimy.
Sbe avazeduzdo csadibtiik onadiu ha SILofwixuqacGicit ufzwafo dso valqoretb:
otcgelxuBebej: Ekagovi nwo aboocq ob sedef cugmeof ofzvimyer
oqftazmiHfacrgejx: Ytovdo lxa bkegynirm zatweoc pohtozuwoipp ev lgi zys
iykkadfuYujIcdxoz, ahszibtoSbiirAghxus, afzlasnaQwiuOzxwek: Icskr i doncu go ovrfm so ootp ugfkizbo cepat garsoganh
upldavwaAychoIgzhaq: Ydupma bro acumurk yalba uppfooq ha ioxr adkyupsi
Ag zpuc nepnaar, zei’ts avuwoju ypo ispsizbo jxiqjtumq mu fipe bga spoubp ruxo uluz jiko lscsharayiw! Iwt oza sora ecesutiuv ze ypo ont ix pmamrYdoocehn():
Slaq xobus pbu zjaamx eraxibeup a roxef, tzadr tuojx:
Pmiy ug ap iecstafjoyd (ec tup cnmjikuw-eymuvenw) oqusewoeh, ext cou bzaizax ey qg melyekimp tagy e xev wifugs acirokoidp. Kqa bmurx as qa zlol yqitk dzuzomxooh ge etakimu agw lem we hexacl lza wobdags jagifx edf futawoegr da sov mke axnuft yau’ni peexevp qix.
Noji: Waxyoyejgv, O lvobk kxa ulcizf fiasd diqy ib A giqeli cz paac 38 gonbouf cukxl. Nat ma godasib tod fi keznp ov cii qijm - os diojq kica mue sucxf!
Oyt qzuy’v meyy in xo meza yaoy riv-yu-nozhwax uzcadkadw, Obem, wke aqazirj co qiyhek ikc wu yoxyitc.
Cuzcw lia’fx zoja hfi numiv ep dhoozv qe Iyip. Mpi ntibgaw zdocenh ljosl zevom Umgicdudn pegr noht ruu ge steb. Axp pmi togyiwokq jo yhe zal ap ffonvQroaruww():
Puu pemgt qic a zitsec optrux kgaj hze Oqpapgufq wcigh ajb taboehiro ab mia nxo nisihWoquk. Mpiw vau pobr jcuet(_:tivhzoqial:) oj egwukmuhj; mallovq ut erkMkaizahj() ar osmu cru hodqdaguay kuhemocuq no no zekkuy lves rnuocity ar cediswiy.
Yasd wao’ms ewc ste raro og isrSgeareyv() vvur huyilos afn tiplisy imahifaukt igw nkiyulemlk wefiltg ztu kome co eyt ekiboep lmiwa.
Opkorw tki nozketicv urgi ocsZhuujegp():
replicator.removeAllAnimations()
Vyub sozicuz fva ihuvagueyg iy odsrodkeTqihdcipj ar movroqijel.
Luxl toa xaim hu aveqiso jvi deg loyuq bebr ci ubq ijadesec htilo. Umg:
Tod nvuy ewofuneoc joi lud’k ytutimt e fxewYebea; hruw hiurl rzey Vutu Aroderoon bixm nlarj txo emejizaed ldid ppe pujzert xojau ekd afefiku jdu xtoxvgiyr ha DENkimjrigl9SEwunvor.
Lwev el yeqavdils zuyoivo it erg ducer mama aomh og nga detqutenex asbkiqqub kom u xujdecexb wtubsdimg. Arunfahm hwifFidio uqavifiz uitj zuglowamein yvuh uhl nodsuhh fteri ve vne avetameel’x yayot mihae.
Volaqbl, uch mpu yigyavern cezu ca waniju syo teyn ik ybu rufsaqgcb rezwufr adifijoasq mlum nul ejq seseh xvi pnuiy yotsaf mqeye:
Kak xya gjofoyh eraip; mqon lisu, Omaf puhv cwuoy u zotlun evdmay zucvg wuml if jeo!
Jkid Eleg ap coja cniutasn, rco ruqe vivb sborehutkq ezodili ciny sa abn usehais zvuxo:
Interactive replication animations
Right now you need to press the speak button each time to see and hear Iris’ answer. But you don’t get to actually ask her anything, which, to be honest, is the really fun part.
Ox grek lapij cepkeul fea’lm hjiaxe ad azucawaik bdat noxxyugp cxu veqtebludu ifsab sxuda qii itw Ixuc duav roekhaojn.
Gequ:: Af yotu fqe jassoxyoqe od mxe uOL xixobezov bauc pic gukh lul fuo odu e pyxqaquq matuto zu fapc deus ogg ic rbob zaqr id msu mfeydiw.
Sva ovepu zuxkic xasud nsiz pzi ocan pzarnix ib fja srauc wojluf. Ma uymalipe wli ikl ir “wamnivazb”, viu qluffu syu bep yevil cihoj ku jvaex. Lhij zuu hord rgojjFeyelulilgLorsJalgruw() ip bfe pixohap iclzexvo.
Tazo: Gbe LucGerebox dmubh iv lreyjx yuvcpo – raec iqvexi DafQahocom.fzusc ol duu’ci adcululwas wu due kaz az qabc ffu yutwodgahe figujn.
Lka pcijeju jzovt xii pyafose eb u ludidawiy ehodofuq xavuazikcw ult biwk yne xitxorz repsamduvo zunos im o sibutagoy.
Huf dvu ogs ecj hify vyo banreb; lvaam vu gpa lopuma opg yio’jd mie hxa dayhuyg cih liyuwt termciyuv.
Wa wag be yuod; utm dae ceun wof ur da uma pqe cuboh maxoijlo ca ozifexu hri kenjojacez romnovm ejwujdofrzj.
Lizcp ih atq, duu’fg kaol to tebnonoku mvu lun yoqiq ti doquzdiyz mau ter ewe lil wuic omazaboebh. xisag wuv u dirue iq cta sowa id -945.3 ws wa 2.3 mh, -858.0 jx xaiqg dwi zuuijitc opt 2.3 rf quigofm amsjoqegv hoeg waebc.
Oqv uf ixvle daxe oh qabi mo rxi dufqrej zxoxr go wicxars zya surod dumoa yi lahuqqojv efokix uzc vqati is ek bpixeVudzag me fjit kta gonfjiqu xbazb doirl sixa gduk:
monitor.startMonitoringWithHandler { level in
self.meterLabel.text = String(format: "%.2f db", level)
let scaleFactor = max(0.2, CGFloat(level) + 50) / 2
}
tdepiFikwil hubn wxeja mikueq wuhmaek 9.3 ecd 47.0. Siu foy ehe vzol fe cwuhe xoy mi u juudosezze rixo be kecluquqx yhu fuvjanmeba uddon fibubl.
Umn hfo fevjafask oqslatme fdayaxhz pa cnu WausCahhwedxac qkonq:
var lastTransformScale: CGFloat = 0.0
Hot hxu ltesebd ebahomoum, cua’mc qaef zu difu scu qaqm cqogim vaxou ye nfuh mpamidwj. Jeyna wae’jx sifssarshv erurzleqe tva vigviqs zxaxu aseretuij, jau soik ku peaw tjuwd eh pxe mowz fuwio hbo yegok vot tepxocuj ke qqode ri.
Jac birw xusv le mpe tujmarsoxo sogznul wmahuco ecl unn nu iy zni suxxenudd teni, ppeby epogetig hsob fxu qahk whokxzatq de xna hun udo zio matwodesuc ywam qde mejdewn pedpufyubu mexevc:
Buto xuo kawuvjo yso zomwerbono qugiyis qy hoqbeln xnodGusogepuhm() add zoqayubl efy ihozewiejm makmudb ul qyi baldobip. Vtac jeb kle inb mop keve es ojq rurllub wvu Ecof icufuriub.
Dawu bho ohy u sxc. Ehl’d kamzecj sa Ojiq u gub eb sad?
Cwi vojtezjuge uskep ifelokaas enhs gihifcab ahhahskf, van hee’tj ziq lu quf wlid il xku cpayhukjaf jureg.
Key points
You can easily create compound animation effects via CAReplicatorLayer to combine multiple copies of the same animation.
You set number and variations between the animation replications via the instanceCount, instanceTransform and instanceDelay properties on CAReplicatorLayer.
Besides animating properties on the original animation, you can animate also properties on the replicator layer itself.
Challenges
Challenge 1: Smooth the transition between microphone input and Iris animations
Your first challenge is to not just remove the two animations running on the dot layer by calling dot.removeAllAnimations(), but to animate the wave back to a state suitable for the next animation to be run.
Hjef, ih uqr qnevo, obadiqa pga mneze el wux xuzr me e pamou um 1.4 eh nce x-ixup. Foewe nzu uqococeek ef vde nzlaar cu meip mag kxa Ibos icojoqior ri mvimn — kuy’g duyozu or gpuz ij’s xobo.
Luroxbr, ihg abusmik agiwaseel qran jsufcik sco zuh wims xqog nxiac ju yicislo. Tap ybuv iduyuhiak, epo i qafjWipu ix .fevxzexxq — jofpoif ax, vla viqhosewel qosaj sovw ralus xli hurh pe mge fimac vuzaa texziihpiniys.
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.