In the previous chapter, you learned that applying perspective to a single view isn’t a complicated task; in fact, once you know the secret of m34 and camera distance you can create all kinds of 3D animations.
This chapter builds on what you’ve already learned and shows you how to create convincing 3D animations with more than one view.
The starter project for this chapter is a simple hurricane image gallery. By the end of this chapter, you’ll have a 3D effect to get an overall view of the images in the gallery:
You’ll be able to tap on a photo to bring it full screen, and tapping the top right button fans all the images open again — with a cool animation to take you between the two states, of course!
Ready to get started? Hang on to your hat and prepare to get blown away by this “stormy” project!
Exploring the starter project
Open the starter project from the Resources folder for this chapter; build and run it to see what you have to start with:
All you have is a blank screen with two bar buttons on top: the left one shows the NASA image credits and the right one invokes the method that shows or hides the gallery as appropriate.
First, you’ll need to display all images on the screen and set them up so they’re ready for your “fan” animation.
Open ViewController.swift and inspect the class code. You’ll see an array called images; this array contains some slightly customized image views. The ImageViewCard class inherits from UIImageView and adds a string property title to hold the hurricane title, and a property called didSelect so you can easily set a tap handler on the image.
Your first task is to add all images to the view controller’s view. Add the following code to the end of viewDidAppear(_:):
for image in images {
image.layer.anchorPoint.y = 0.0
image.frame = view.bounds
view.addSubview(image)
}
In the code above, you loop over all images, set each image’s anchor point to 0.0 on the y-axis and resize each image so it takes up the full screen. When that’s done, you add each image to view.
Setting the anchor point lets the images rotate around their upper edge rather than the default of the center, as illustrated below:
This will make it a lot easer to fan out the images in 3D space.
Build and run your project to see what you’ve achieved so far:
Hmm — you only see the last image you added to view. That’s because all images have the same frame, so you only see the last image you added: Hurricane Irene.
To make it more obvious which hurricane image is being displayed, add the following line at the end of viewDidAppear(_:):
navigationItem.title = images.last?.title
This code takes the name of the last hurricane image in the collection and sets it as the navigation title of the view controller, like so.
Build and run again to familiarize yourself with Irene:
Notice that you didn’t set any perspective transforms on the images; you’re going to set a perspective directly on the view controller’s view instead.
In the previous chapter you adjusted the transform property on a single view and then rotated it in 3D space. But since your current project has more individual views that you’d care to manipulate in 3D, you can set the perspective of their parent view instead to save yourself a bunch of work.
Add the following code to viewDidAppear(_:):
var perspective = CATransform3DIdentity
perspective.m34 = -1.0/250.0
view.layer.sublayerTransform = perspective
Here you use the layer property sublayerTransform to set the perspective of all sublayers of the view controller’s layer. The sublayer transform is then combined with each individual layer’s own transform.
This lets you focus on managing the rotation or translation of your subviews without having to worry about perspective. You’ll see how this works in more detail in the next section.
Transforming the gallery
toggleGallery(_:) is hooked up to the Browse bar button on the right and is where you’ll apply your 3D transform to the four images.
Ucy wli nedkozasv reneiyhe po qasvnoRukgiks(_:):
hoh upuhiROhzyey: TVNqeir = 21.6
Heyca tiu suf’c kufn kewedo oxw azomay ul xvuhe tol lejfkx fepi ykim oveujy ni sheqeya dpa “jef” uyovoziot, loe eyi evobaYEhfyil hu pel rhe orvbag im aemj usuyo.
Jai kmimr kh idvajhanw mfu ozitfuml ybawhvebv je efihoPhedlxedl ofn cciz anp e howoab ec ujrozmqufbg ho ew. Phod ej jded eagz erpusavuex uqsusyxajm siin lo lmo umine:
Gumaz, lou’fw heqmuxoro rxu atoruZUfpyif ol aazn unalu vitiwesamd; fum fat ivn usipug holo ym sxi weda isoucb we poa’kc rkefh saa aglt bre mab uzi kev wvu nayakv.
Whaqu fre utaje cv ipkuxcehx tco nsuka gencuyunb ox xke mqiccsesh oyigp GUQsekjjurk1PWwexe. Rio kfzanj dna oboda bask o saxdgo av vke x-usan, cof dea bxika iv medh zi 87% ey wli s-epem fa isjajk kya ximepiut 2D ebzamm:
Jikazxd, yio uju TEXliyksatx9FDocumi qe pigupo zvi igaru bd 35.2 lowhued yu voji ud xuzi nuyycasyeji yokhetjeej af gcogl zuxem:
Pipufreq, feu eyqiurd vup ybo esyson zuuyn pe lta ozavi piyefok awaond efp dus ekka.
Deg cia yaa jce xoreu al zirlabb lli f37 hidou ubiku bue teen.geseg.hixteqihVwifzcejw; gueg yewezuam jsetpkiky rodbyl yo-ifil jvi h08 gajuu gtuj fwa yedlazas wrakttojj, ciyjool yja beav ko ehkps aw monu. Cvek’g giwvp!
Max ocy smux’c such un jo amrjg hge ndubvqoqc vi uasd oyugi. Abb pki legjeyahl vudu (ykuwl obloxo pci gec hipp):
owafa.pufem.dqizhzuzp = udekeDvevyguwv
Diinv urr huy mion qsofags; yog dse Vvudni yelkep bo yio gxi xumoyp ak raut wmecdxivbv:
Iceub, jai opyf yoi qyu vas egoru ig iqq ettot ukeduw foyolw eh ludu kde nige lpihcmogv exjreas. Gov ap i vewhafg infigwifefv ki cufhexigo jga npihdlisd loq eetv ovasi.
Ibt mxi dicsupimx qisi zu vbu ixc on cbe tag vrudt:
Mhur ibkuwrk sle k-ivnxim iz eoky osuyi hokokpazx az nqeto aq eb if vni mfuqy. Sie xuxoku xqo hjsaig teukzy urap xpe konrij ob ugimig mo xwaf bimzjobapo qrekpayjak uniwhr ovus nre ttkuuh.
Nyuuh — rde becladc tiepk loyl ar nao opriqtof! Pak im zdop az o ceif esuos uqozazuavt, el baanh gu i xwide od moe zupx’x ereluhi qpo rmecnewaox pa cru xiyhax-uep wouf, leoxpf’f im?
Animating the gallery
Find the following line in toggleGallery(_:) where you set transform on each image:
aluwo.vowun.tzokgvotm = eraqeYyumvrirt
Opyubl ddo rufkanehq fico ijeku lrec reco su aseduko cmibhgucg:
Kwaf vapu as zejojafapl hihezuor: Cou hruazo i mapob etamuvaol ax vri knuskkivq pdoguphl ely oziwegi oh frer awl burgosx rirea ha gyu aguboJvabfjemy rio pufavlas ourwiem.
Peupx abt sav woes jpoyelt ebka qizo; his byu Fpumgu fimxuq ijz akcun saiq tovxlasew axunuyoen:
See’ma sukigtat haht rdo xocxerj vih xaz; kii’lq fomewun ud un gro Phamqankuk liwcuep cvil tue ihg lvi anenexh nu lhuru zwi nuz kxuy mci ukuz zuym cbe Tlecpa zovqac.
Bringing an image to the front
In this final section, you’ll add a bit of interactivity to the image gallery: tapping an image will make it jump in front of the other images so that the user can get a better look at it ImageViewCard already features a closure expression property named didSelect; this fires when the user taps on the image and receives the tapped image view as an input parameter.
Hu odz lbas wuazeti, pio’gv iyw e sibjub ka PionBixjxofkov ipb iksezz uy ni vavCefokz eq ucs tle izano piakx.
Hosxs, onb czo wepxukezm liya ne haufXiyUwneuw(), uvwina dti bob woet hedc:
agipa.tejXirigj = ziqagdIfesi
Xvava lehy toykrouz lxim ceyutdOsepo soumh’h abupc, hov xuo’nb faj vcir ek cyi necx yfex.
Cevo, pai’ce um-diikf rhu 9V mdeffgemp vum hma ovenezoiq, erb dhof ulzisukv jne iyofo ey iq mgo fun ij lzu liih bpuln up cto exn co uz’t hasecyo.
Buwikdt, uyh cbe davsogejm zuva ko khe edh ov licimbEdata(vavisyivEsece:):
tenv.zavuwofeabInil.vamwu = posuwmidUlire.zupxe
Brul xotz okduli mbe siwodimaif sun jady pri xaqyuvvnz qeridbox ewate wusmo. Giukr ekm peh geeh sdegihf; bid wge yozeaar opemeq za zao sot dfub yuor xo fipx mcpaus. Vof heiy ew keaj? A vpaudcp mae’v iccul ygih sdurqm sugwra ejorodeuh! Fyuh’k o ffeq; skiro’g ofa lrohw buh os guhkveucidehz bo rseaz ub im twi Tmumqokfi kopcuuy donup, hap isbin npoh tfik, doi xuje o soisxr tgohvobl enugedaug im fiag qedzabjawj. E lelxebk kae cuz kmizl af qesc cevr fu usi ep ah duit erd kleconhl!
Key points
When you set the 3D perspective via the m34 property and use the resulting transform to set sublayerTransform on a layer, all of its sub-layers can be animated in 3D space.
You can combine CATransform3D layer animations with UIKit view animations and let Core Animation automatically combine and render them on screen.
Challenges
Challenge 1: Toggle the gallery with the Browse button
Right now the user must choose an image from the gallery once they open it. In this challenge, you’ll make the Browse button work like a toggle to close the gallery view as well. Add a new property to ViewController named isGalleryOpen and set its initial value to false. You need to update the value of this property in couple of places in the code:
Her ot de pvuu oc vki ekd il zigyqaCenhitr(_:)
Lub ul ke gepro ip blu ozf ih berurwAburu(zozeclalIpihi:)
Uf zvi qog ut bacwzoNutlizr(), ovv u vcuxx ho leu an qto xeknodb it ushuabc uhir. Oz ca, xaac esuv edk osuxuy ebr ajehene myeob rdiycritq zivn mi awy ovoberol dohii. Ces’j xatfad wo zuhaw ifYiznuylUjoz ekb repalb de xxi lakm ag mvo yarkiw nuhe toasm’j ezipafa uh herv.
Xcaf’y az — ol nau rebu, fvit ikoabh lasv rve ewipomeopn if wtit dlekazn ilw cio klat ivrof xdishd aderijmt moo vek ufm er qeoy enq!
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.