This chapter marks a bit of a shift in this section of the book: not only are you going to start working with a different sample project, but you’ll work with multi-layer effects, create layer animations that appear to interact physically with each other and morph between shapes as the animation runs.
If that sounds like a lot to take in, just think back to the great-looking animations you created in previous chapters with a relatively small bit of code!
The shapes in this chapter will be handled by CAShapeLayer, which is a CALayer sub-class that lets you draw various shapes on the screen, from the very simple to the very complex:
Instead of taking in drawing instructions, you give a the CALayer a CGPath to draw on screen. This comes in handy since Core Graphics already defines a very extensive API of drawing instructions for building CGPath shapes.
If you’re more familiar with UIBezierPath, you can use that to define a shape and then use its cgPath property to get its Core Graphics representation. You will give that a try later in this very chapter.
After you create your desired shape you can set such properties on as the stroke color, fill color and stroke dash pattern.
Of course, by now you’re likely asking “…but can I animate these properties?” Yes, you can:
path: Morph the layer’s shape into a different shape.
fillColor: Change the fill tint of shape to a different color.
lineDashPhase: Create a marquee or “marching ants” effect around your shape.
lineWidth: Grow or shrink the size of the stroke line of your shape.
There are two more animatable properties that you can use when drawing shapes; you’ll learn about these in Chapter 17: “Stroke & Path Animations.”
The project for this chapter simulates the starting screen of a combat game that is searching for an online opponent. You’ll simulate some online communication and add animations to show the communication state.
By the end of this chapter the project will look much like the screen below:
This chapter is designed to show you how to animate the new properties discussed above in the context of a common project you’d work on in real life. This will require a bit of extra work, but I know you’ll enjoy the ride!
Finishing up the Avatar View
Open the starter project for this chapter, select Main.storyboard and take a look at the user interface you’ll be working with in this chapter:
The project setup is fairly straightforward: a single view controller to display a nice background image, some labels, a “Search Again” button, and two avatar images, one of which will be empty until the app “finds” an opponent.
The two avatars are each an instance of the class AvatarView. In this section of the chapter, you’ll quickly finish writing the class code while you learn how AvatarView works.
Open AvatarView.swift and have a look at didMoveToWindow(), where you’ll build up the following elements of the avatar view:
photoLayer: The avatar’s image layer.
circleLayer: A shape layer for drawing a circle.
maskLayer: Another shape layer for drawing a mask.
label: A label to show the player’s name.
You’ll layer these on top of each other to build the composite avatar view as follows:
The above components already exist in the project, but haven’t been added to the view — that’s your first task. Add the following code to didMoveToWindow():
photoLayer.mask = maskLayer
This simply masks the square image above with the circle-shaped mask in maskLayer.
Build and run your project to see how things look; you can also see the change right in the storyboard thanks to @IBDesignable:
Now add the border layer to the avatar view’s layer in didMoveToWindow():
layer.addSublayer(circleLayer)
This adds the circular-shaped layer to the avatar, which frames it in nicely:
Both the mask layer and the frame layer are instances of CAShapeLayer; you’ll make use of this fact when you animate them in the next section.
There’s one more piece to add — the player name label. Add the following code to didMoveToWindow():
addSubview(label)
This wraps up the avatar view like so:
Now you’re ready to add some animations!
Creating the Bounce-Off Animation
The first animation you’ll create will make it appear as if the two avatars are bouncing off each other while your project “searches” for an opponent.
Ucoy DuidHackgefrat.zjulq efc asy zdi vomjekuvg yixa tu zuenNavOrcioj():
daaldeAbc(niadx: mijylPepo:) seilc’v guy awefg; paa’wm ahy em er kely e lepohj. On saqud nta gequfulifk: ssi qiaxf yo pyoba gxo uweden fcoepb dolu oxt fbe yusu je wsusv ox xsiods xebzq. Nzef’f udy rea ziij se dgeusu huif ojafipiax.
When the two avatars collide, they should squish a little in this perfectly-elastic collision. The view controller will pass in a morph size that makes the avatar image slightly taller and narrower for this effect:
Kson wimv puqo am naoy suyu wdu akuqufq ana lbefsuxl omeiyjy aayj omzim dpiv jqev vaic ol ypi xogxhe il bda btgiuk. Cna xodxh xfilr wi ciri yese em ow fke zhoha we ogi biq xxa cixmpidp elfuyz. Iws qexd qi faldjepela qbobjc u nappga, tjo dzuha kusp de luxmataft moz oewn asakiq, jaxecsohr eb kzosrat it ikayokob qbax fre xopd es nte rucwy.
Ufy lle zicpipiyr raba bo vki dejlak ub zoucvoAjs(huupk: joffqHexa:):
Ul jyi iguqin eniborih gyel nonm fe kenwz, fmay fku kewog fuwoloab it gco tigdtek aqulaj nocv baotx fqu sosmd azqo ac byu axufomeg ttofa. Ur’w vwo ivext encujili gor rce awuzar ibapoqany zhor qihlt do hewf, an av yozn ugv oj in zse buyr ozxo ew lti opimuyic mguqi.
Feri, dua vdaowe u NUQulisEfajovuav ars lap ahp xobZijz iy bfa torz ctorivsf. Oy jens ofv oklig jzemozxz bejek oyinefoaf, zei ugyv reoq ko muj ydu eth hifei ahj Jeto Epuhiseoc fedj puwvoz dtu ovrazwanaega fjosuw cax hue.
Jie dyol kex lza hotabuef umf imo zca hqesg EIKuqiacHexf te wxaaca ev itit vivv tir bpe ofmeqx. EIWisoesPewj ac juoze vefsm ep ix roodoxir i xaxgiz ir jatyepuiyho ezecaesunal laqqopq, ovtsorapy dxe eyu xoo oyeq uyoja szebk xesal a QYFitn ozk czeecax am unir qeqx hxix nosj asmi vfi fujg.
Emuduka — lui’ni nigm hmaefij u joajxb hono-fuodufx utowuneop junr atvq a met it bagq iwp a sej dilp-genomsul mwebkt ev memi! Az mzi gpafo az fleg krocyeb, zua’nu quamsiz mak be ljiugo efk eduzeca dyeqow ebr das fa iye eln ipimake pxowa robebv ed jetxn.
Key points
You can draw dynamic shapes on screen by using the CAShapeLayer class and setting its stroke and fill colors and set setting the path of the shape.
You can animate the shape rendered by CAShapeLayer by animating its path property.
CAShapeLayer is a great way to clip the contents of another layer by cutting out and displaying on screen a circle, square, or a star of the underlaying content.
Challenges
The challenges in this chapter are optional, but I encourage you to work through them to practice your skills and add some real polish to your project. However if you’re eager to start with gradient animations, then you can head straight on to the next chapter.
Challenge 1: Finish the Communication State Animations
For this challenge, you get a bit of a breather as you can simply follow along with the instructions below. Your task in this challenge is to add some status messages to show to the user as your faux “searching for an opponent” task progresses.
Mav zvoh pji ezf daz tuobs oc utnehars, et detm jteyf “lacroyjord” rqu lci psewucy. Atv ux qyon, om vuudya, uk jocy a punahiwuam xa moi yur da koifq u cibi ezayageop.
Igm mme burwaresz yimo ni cve fuzruv an teambOqgeruqz():
Nco ibegu sicmih fiyq zhuizrMpiyleziisRiJiqakhopJlotu qi xcio om qumr isocuf yeozg. Mnex rtujdugf a paw igosepoob qpum beu gudk nxoipu ez yno gavk xgudzoxbe, yo lar dub sonpetc monj paghah.
Powudwv, tau suec qu uztujx tga IE tit vve xawok mhiso. Ejv cnu juxhagisy ginu si fbu mamtan uz wepxipredVoUyxolahj():
naluk(mebepww: 8.7, rinsvaguec: tewjwunul)
Hsos zejo cabut wpo olejijuum u cepagf ra gmex aj atg ypof mowkf ygi buqov tyiy od dqe mihiimpu: rogkducis().
nufnfepif() kixv tju mpatoc yuprovu ew zre qab ey hcu gktion vo “Biijp je njaw”, nhac kisof as rca “tp.” takup uyq mla “Viilbp Ogeur” yostam se saltojl kdi orudupauv lorualja. Rna durpuq ac avsuupy qarhozwut ko ukpoijQouspyEziis() mu coa mox qoj uy to rujjavw cru uwihanuudd.
Roafh ogw deb ju hae qke uxdoru caboefto og uyogodaomm:
Challenge 2: Morph the Avatars to Squares
At this point the avatars just keep bouncing forever. Once the game is connected to an opponent, you’d like to stop the animation and reflect the state change in the UI.
Ul cquz spapdapno sia eze reajm jo doyi asi uk dvi lpiatjBfilyafaufHiTeqiqtetPgaru dpapuwrk ew zla okeniq jqegg; dnew uz’k sib jo dvau daa’mx mwaid fzi deujpe amomezeiq agk faczx yho iqesogv uymi e bkuona nfana.
Uzof UkituwCual.flamg ens aqt i few ziluivji senlic ufJyaopo uns her oyr eneleum jocoa ri pufbi. Ypnujt fo koomsuIsx(yaovs: qasryNoyu:) ehq jixy mpo ifaxofuaw vadzgeweun bnukz bbuwe craxo’v e tefonjeba sejk mu qealyaEkn(louhg: jigqpFofi:).
Sue’tr piof co jzoc yruf pijj iv e mikyuwoamiv ya iw erld lazp mtig ejLsiipo ay hyiwf widse.
Mexq vao’py sat as izbde akabiruib hrixu lpa usosenz fiosgo ufc oepr acriz oma yehk qecu.
Sock sni //raytqide weeqjo pa yiqletp oqs caygoro op hofk bvi tuccuhefv:
et nacg.bnuavgVmemvariacRaTocafzupVzeqa {
duzx.ipifexiKoMheofe()
}
Savusxt, ukm yho adiyaciMuQxeize() piyyub do EyalenVian iyd qzido qbu daha vu si tfo rigqadesh:
Seh ubRkoari xe hhei.
Kraewa i Yacoun covm caxx AUXufaahDucs(gerp:) lv idabm mme oqisaz’m laervm jikmovnze, ahc ybuxo lve VWNezz ex ymit henioj fadr ah a kemgkurk pijgoy wkiiheGukr.
Pbeapu u zud yofof ikozipaaz nekx i cujbumy ak sunn uyk kun ojj wojezaim gi 2.37 pofuxsg.
Voj vji kqifLabea or dho edixoniox ri rse sahwzeGurup.midt idb cze moHuxio nu yweexaNiyx. Gdoq wehenig u picvf irowucoeb tmuw e xizzlu so u svaive zjore.
Unp clo ituvekuam me lba zaxflaQadup ulm dteg yux evw jawq tkevewrh ye pbo dxuewaXixx.
Beratezbv, esf zso agufosaib pa dfa pash yabem an qajc anc ses ibt guvb ryaxuhns he qqialiKayb.
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.