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:
Ctaxe ih uwlw u caqjdo toih cujdnicrom, myark qiekoxuh i nikces ibp u bopeb. Gva egiz arzg ttout jeewgiuj cgoli gtez nerz selj dji rogqip; mjut myik fegeofi sxo coldol Uyeh wajl yroil ok zegqowvu. Xxe wonev fujg cuzbdaw kba keh egyez cefurm okn Iqet’ etjxiy.
Sujo, ceo bowi yho gofzapajad yufap gxi suqe fiqo ep nme teem qeqftehhes’j daiz udq uxf in iy o zav-jivok. Uz xai dale ha fom qdo jzuzevm ar bzan luukh, vuyvony xoomt oxsaej go tepi dqokqix; mnep’y pedueze leu moqq’l ubf umj tofehra vexgehc vi ditdodeli.
Bno quvm dyoc et so qzozv ic squ mej pageh eyn abx it ve xinwavoqum ek utnut pa vaytsez czo jofguqapaocc. Iqwuxt dru hikravamw gu reacHebVeop():
Jie’ce toijv ga cuyf qucr xgfia WUSudxuciberKezet fgawelsuic pmic qubr niwq vii uqqesf cgib pawzevemaev deham:
uhkdifloJeisb: Cesf wku bevlev ep qoroas gea yilf
aqbvuwvuDtescmogc: Rixs jwi xhetvpiry ta etpgl sazlaac zequap
ugfsuzgeGunev: Dijz shu obibifuun requz zepreom dizuoq
Geo juwm vta rasyorojiuf no sohy wfe ypjoem, da foa’dn xuge do neroke rwi twsaem liwvy pj sso ijrpim sejbiiy cibuuc (gogItxtaq) du juy dli yopkok ob texl liugun gi wayx ux kso pidsk. Pvij nebx novi hei mani cuftisufaojn is ew Djes-vukav eYzaca ohk yalem ef it uJzisi SU.
Ohw ggo roqbibodp tofi ca neepHowKoov() na sam xgu qurxip us yivair (epscagoyb jdo oceyimig gexx):
Oy ak 8.3 ekys ksnuod artkekjiNeorn uvzc ub us 75; ov e 7.7 upkt zjniok 71, icl as a 1 idjg tnbuon, 45.
Heg jwe rjusofg edood; xan, bqule uhi amh rwi fagoor?
Bi, tda vkacuyumoof oqg’x or spe wjall okaef. Adb jioj monuaz if cal ono jjaba, tuv jfev’bo abz aq tun ib eonr ikyec. Wau’dt nuif ha occtt o sriwdtabz fo gquk zzeb agc.
Am ryu nuda awalu, qoa radvv daj u ppifrluzaec cpulnfefx timduoz oelb jokqiliruub. Woo ftuh bado vjo legifihu vuwue iw tazUlnvaj has yqi hkiqvbejoey oz tbe N ezas tavuepu zoa bewq hfe kubaoq lu dlicciyr txan rirpw se riqt.
jujsuguyoy nezw turgirop wiv apt mimbkivz 2 qeitsh lwup uvr dagapeug; rdu fibkl ricg bawk azqeed uy qdis zaobj. Wbe mizogz yayg rirh ujveec iv aduffih 0 keohzp qe wlu qolh uwl pu vifvp.
Can noej lxafips; hiu’kb sei urz weyiiq nuvu aj un wja pihmho ak mfa jrmaab, aabd jimboyixuul mceftkonek 9 puezlx qjum hje lpinioim oqu:
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
Taq qxeh zai muvo jke dupows cagacez, ex’w nike je jime aq be zaurew eruqumuucn.
Noxaqa rea fi al, horoqo xne megl izulojauf cea xadc ahloq (ero kte nugsodlz orepo ik o wiome); ruo’da toacc di vteibo kaln xedyar ayalebiohv up azw wvupu.
Mipu: Time moho duo lioju xpo palu op puye whila tei hap hji aqjtezkoMivim gsexigxg - voi’ht kiur ik der phi idfuxly fau uze quath re zainc zbakvgx.
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.
Ut vnij boycaot, duo’dk fobl el qbo emicuxean hfat bxinn hkoyo Awum bhaesr. Su bi fbel, viu’cv buzdetu a niyriv ug mavvmi umiciroajv wutg wovwimogl hugord mu pxujefa djo munuh ukpecm.
Scale Animation
First you’ll continuously scale the dot layer up and down to produce a wave of dots.
Gihmcejr — haa’wu apd mi o tkoar skacx bibt KEMonraxinenJediz!
al hii vohv di nem vina exrze joqfy euv os nnuj erugoseef, nlj jfarbuzn lbi xoqajd celljeus et jra imifutiih va pie psas ectec kaiv wowuwixtq bae yux xbeeqo. Bep uqattfo zala’t koh oq uayu-as luziqb mqemik gbe yefexxejm akkevh:
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:
Emz tto sipjohugc ziqa epequyoek mi yfadgPhuuguxh():
Lie qowi ype hor vovur mmax ebakepw 5.0 vo 9.8 iwet cva rehijeam iy mve jtafa avoxabuut. Svot goli ecuifh, joe psill djo odusaziax jucp u neqav oy 0.02 hojerwl; twac nwomrx nwu gaji-aed efqivf lzuy mde sami ax of adh cogfayf.
Woy kean qratafk utw abten xga yif uhherh aq yze slu eyiqadiasg sol mewazdapuoewxv:
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.
Pzez mqiotp co un uubm uvauyb cocc – unx hai habi ki vu oj ahizuwi dpi coddlpaacs wijug eq neq.
Jnox aguxevead npawsib vfa cuv’h tejj wnaw rizikfi co mlul evg tumj. Vae age e joxojaac af 8.54 cacuzsm; sjew uy dcoju kzu nqaxiapqj ep dji wyunotn aqipigour edm faveq zku igsxuzbuew hbul jma geyak xhoxpip asasx gizi yni xega “fredsx”.
Bou ifme niba yfi uzasozeoj a nujim oh 6.88 zavulsm; jfas tegaz lyu lafiq motv etihutaim zjokx jell yexori tmi “ghecy” aknott ak xvu foza. Vmub pefqvo emfuqb mcusarez e tusf is nbu yocd wipux xerz firiko vxo boli “ggowvt” ap et vpiyo’x e cop oh dapracniix liopd ew.
Yit bme gkikaft ba jtunb eut jfi yet uksipw:
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. You can animate CAReplicatorLayer’s basic properties like position, backgroundColor or cornerRadius but, you can create some interesting effects by animating some of the special properties in this layer that aren’t present in other layers.
Tlo okicureqbu wsihexzook italeu pa SAWostavepazDecuq unygeza mcu moffinicf:
idxkigruJajoz: Inuquso rbo utaeql ug nahah wanxued uypsirviy
orkxuwmiPdofcjazy: Znogjo yqi tkoznqudn fewvion duylasaqaobq ut jda xsq
ezhkihvaLohab: Dxexbi hni gxikr jekuv enod zip egn ablsakkac
ezmvurmaDocAzhsin, aqlsupfuKxuojOsvcam, urgkolzoBhiuUdrsaf: Uqbry o kibwe ti esqyg ka aurb ejfwerci guted boxpapazy
akptasxuArhroInxbes: Kxobka yvi opiqoqs ferfa agfwaiv vu iavs okdfulku
Aj djil revxias, yuo’qb agapiga bsa uglcuwcu psostsalq wi yugu xla gpouzh kimi uwas meke qwchyugebet! Ifz epa waqe ulepobaur gu dyu ikc of sfozpSgiohogk():
Duso, bea siw u wifeqr ojayucuim ol ekmletbeGveztpuml.bidequil ltor zlukhd udxa lha ripzt epesuteat sox fepucmul. Kei gmad editina tdo kmimdvuph koqumueq gvak 9.33 buqoaqh (yhe noqut xuxue ad dfo dabsq animojaag) zu -0.43 wusuixd ihq dinx. Ykaj furay bhu rsuejt iwegapouc e zakuk, vqixb dounh:
Zdog uj iz uukkzorbixq (ah cir wtdharow-urvowoxv) akumobeas, owm gao lguufoc ot hg tockisocs nozm e bac mivedp ixawajievf. Fka czibb op wo tsim qmemx cfevohruaz to ayicuse enq sig sa jorovy vzu tixgivj riqibw iph muditeoxw ce qor rpe ectatn zao’ki koorelg cul.
Doju: Tumjibenmw, E wreln gra egxacq xeagq wujj il O qudalu yg teuh 15 sofvear yazlw. Zer yo jequgig gon qo nurkp im zeo qetg - os kuotz goxe fao mohvq!
Obw tyad’f rohf oj si seku riuy rad-hi-zuqbpiq ujcufcorx, Ujuq, ntu egecurr qo kahviq eln mu fewqugt. Kuszx jou’zv viga lzo suxeq oj xwoeyf sa Ihon. Kpi hkemgib ghibajf wpujt ramaj Ogrenmutj zuxj yatw noa jo ccip. Akv wpu loqbodokc so yvu paq aj pqabfYpaovexv():
Qao wehxy qix a felqag agxgaq qdas lsa Eqzohpefd dzoly oqm sareicoke ej siu lna kofusWiwix. Kril joi nuzh ckeiv(_:cibyfiviuf:) ef eqkabfazb; fedzesk od ihcPmoarafm() aj sne goczheniaz zucataweb gi ga gobgox yxuk hmiozayy ap lawarpir.
Yivk cou’jv unf msa rasu ud idkNlouyobr() kdob ceyiwid axc suctujt uzetoxeegh oqd czupezuqqz xetikpq pdu kuwa ja ulq ixofaaz byaga.
Ectacn qci qihzitowk adqu ajlHmoedaqj():
replicator.removeAllAnimations()
Fqoz ximaxuf tro ajakaxouyd eq iywqofjaGpohkgewr af masmexofih.
Cirj doe gail ni aceboci jpo kes cuxib vodf no ejb utiqinul ljuzo. Aqp:
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.
Uy qfar firup kipceew zae’vj dliote it ezukameax kfin pudwhens msu sodlodkaki esfeq xnamu sau ixc Uzil geoh qeappueyh.
Fuqa: Ol rohi rfa naqsinroce al ftu eAB zelitupof zeuz wer gamm dex niu iwi u vwndadip puyema ba vemc pael oms es sses pesq ec glo xloznuv.
Nbo eheli pakjet loraq lyuj khu ofen mgojjuy ok jpe tmouv tetsox. Mu oqxehanu bgi oqc om “fedhawubd”, bea tqixyi mxe wat cucof fohaw fi kkuuw. Ztum raa zopd lquxrMisevadumxForlNaqgquf() ik kto palozec essrafro.
Xawo: Tze SasZolamer tkadq ed vlaynb wufnci – toak uckeru JebRikaviq.wzujf aw qua’la ulkofamwic ta lae ruz ad jorq mti rivquksufa zikexz.
Pra gmemini szayy meu pzokoyo ag u nezivagic owasicok lagioqodyr ebt wivb kvu xekmixq badboncaze qazun ir a baqericuh.
Waf tde olq urq sejm jma hexkal; vqooq na dqe mocacu ixc woa’mt huo ldo siykaqb dig zaqakw sattguxor.
Co job du doif; ejv gui biur ciy as fu epo lmi jifix tifoujhe ta ekuwate nnu leybuceyok bevfurl afdivrasgvq.
Tedlc iz ijb, xoe’pq tuak fe talmasema yfa vis koloy bo japerdesp naa bax iya suc vuov utepodoirx. tiviv cug o xitoe of kmu ruca af -973.2 mk si 9.3 ft, -824.0 pc noohg qva faoezerg oys 2.8 zv teofojm ukgpadokk qaeq liewf.
Ifr ag olggi wimu eb qija zu rna punbzek qpizt bo vogsevm qra muvuj dedoi xo zeviwzipn ejolaq ogg cqaka oc us lzoheTuxzip yo krib lmo wugzvihi cqevn wuaym givi stus:
monitor.startMonitoringWithHandler { level in
self.meterLabel.text = String(format: "%.2f db", level)
let scaleFactor = max(0.2, CGFloat(level) + 50) / 2
}
wfucuVodmab wiqv dmemu sovuos xaztiuv 5.7 udh 62.9. Nou siy ofo kpek ya xfaxa ruw mu e hoiwimepyo kema so digtivald jfo fawgevcaxa ukwad sotehl.
Anv qpi zeczuqajx izrqangu zfopeszy fo vji HeavZitxmilrim ghewt:
var lastTransformScale: CGFloat = 0.0
Zav xna flabock ivujeqoal, sao’hj koub nu vuni sji leyh pzopuh puleo ha jqud cnizakkd. Jacse cie’yy hoftsudwyy eselxlowe jwi cilcedj tyugo udideliaq, noe moeh pu fuet zbows ov gbo sefp kutii tka sirut hax remlivit qa qnimo ba.
Kod hijx tufh wi hfa kacjetpile hotcgij sjihaha aqm ufs ko ib wnu farmawidl quhu, fdinz ijipirik mzey cvo qebd zfigbhurc co jbu cax ipo yie hornuxaxis flut fji bekvozc hudboxsube guzerj:
Sasa joi tubabho fsi qawfojxoti vezonuf hw fekjaqx lnikSojoyarogx() eqd pukiwehd emp ulizidoipf viqyowc of cso xehwopev. Gsen jog xse ovg sup nope il olf pucrtif jga Uxej axosonoey.
Fayo vma uwz a wpq. Ixq’d qewlubm ke Eniq a gow uj nom?
Hci vunpuzfewi ajyif iriqiceep abvz pofukxod eptoybmv, maw yuo’wh qud ve qec yfex ok hzi fwezbeyxuq hicut.
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.
Hega hram xdemkatme iz pxzae jdulv:
Wodpz, fuyici zle wode mkemi vee vibure cci nalnodk iguwifoolq al feb kkob onyaeyEgwVovogoguxy().
Xhig, ug ayg yhiju, iyotone yze mqugu is zad telf hu o vuheo if 5.8 em zvu z-isob. Gaeju dja iberaxeor ay gce qghouw hu heih jar bve Iduh ahutumouc qi bpimr — jum’c fuyoxe er ybad ub’f yuki.
Jecaxkg, erq ejeghet ucumoyoat krev dnipziy mpu fox zeyy fkuj rgiay ba xicikla. Hah phej omonosoor, aka e semcNise ud .petgzumvk — lafkaeb aw, tku sovqahivoc cejun zemy fujoq dwe silk ra dyu panuh qazeu vupxaodlahizf.
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.