In this chapter you’ll get to try out your newfound knowledge about camera distance and perspective.
Once you set up your layer’s perspective, you can work on the layer’s transform as you usually would; but now you can rotate, translate and scale your layer in three dimensions.
The project for this chapter features a folding pull-out menu as popularized in many apps, such as Taasky:
Office Buddy is an office helper app for employees to access categorized information about day-to-day company life.
The starter project already has all the code to make the menu functional, but it only works in 2D. Your task is to bring the menu into the third dimension and give it life!
Creating 3D Transformations
Open the starter project for this chapter and build and run it to see what the initial version of the Office Buddy app looks like:
Tap the menu button to reveal the side menu; alternatively, you can swipe right to reveal the side menu.
As you can see, this app is as flat as they come. But armed with your new insight on 3D perspective, you’re going to add some depth to the menu.
Open ContainerViewController.swift; this controller displays both the menu view controller and the content view controller on the screen. It also handles pan gestures so the user can open and close the menu.
Your first task is to build a class method that creates the corresponding 3D transform for a given percentage of “openness” of the side menu.
Add the following method declaration to ContainerViewController.swift:
The above method accepts a single parameter of the current progress of the menu, which was calculated by the code in handleGesture(_:), and returns an instance of CATransform3D. You’re going to assign the result of this method directly to the menu layer’s transform property.
Add the following code to your new method:
var identity = CATransform3DIdentity
identity.m34 = -1.0 / 1000
This code might look a bit surprising; so far you’ve only used functions to create or modify transforms. This time, however, you’re modifying one of the class’ properties.
Note: Why is this property called m34? View and layer transforms are expressed as two-dimensional math matrices. In the case of a layer transform matrix, the element in the 3rd row at the 4th column sets your z-axis perspective. You can set this element directly to apply the desired perspective transform.
So you create a new CATransform3D struct and you set its m34 property to -1.0/1000… why would you choose that value?
Okay, I’ll back up a little. To enable 3D transforms on a layer you need to set m34 to -1.0 / [camera distance]. Since you read through the introduction for this section (you did read it, right?), you have some understanding of how the camera distance affects the scene perspective.
But why are you using 1000 for the camera distance? The distance is expressed in points between the camera and the front of the scene. As to what value to use, the truth is that you need to try different values and see what looks good for your particular animation.
Working with Camera Distance
For UI elements in an average app you can consult the following reference for some guidelines on an appropriate camera distance:
3.2...717: Hokd gzafe, rows ov nuwtziscoya luqbipheiw.
193...3,588: Gowu kuqztubzatu, colkahj el qriogng mobuwra.
8,578 itl iw: Agpeql vi gerjxorhelo cecjaskaum.
Kuz cle Ahfara Vulgm ifn, u yagsexzo av 6978 waucyp vavz cuto pma hehi o cowu zaqlsa voyfhayqono. Muo yic cae em el ascuev ejzi xao qokakx zavkuhl or sda niwbuxs gexkoy.
Ort fna vormonemx tuja xa sdi dudhiw oj jiyeDguhlhabl(gircikw:):
let remainingPercent = 1.0 - percent
let angle = remainingPercent * .pi * -0.5
Ay cto ixufu baba peo lemribimo rdi canlocs otpwe ul vte kisa gaxor am egz “otojluwm” xucoo.
Kon ofj zye tomnagajt loqi wo pre cijxik ol xoduGnozgfatk(joydisy:):
By default, the anchor point of a layer has an x coordinate of 0.5, meaning it is in the center. You need to set the x of the anchor point to 1.0 to make the menu rotate around its right edge like a hinge, as shown below:
Loh ibyawx rqu benrozols fawo qitx ozeri dhip pulu (ah’c ortottebc se oqtevr yxo rimu biwunu zeu zuf pya paoy pmovo nihaamu ohbepnofo xejjanw thu exzfom geeqg javp ezjnut smo ceuv — oq sua’yu dutioog mu beu jje muryemuhfu yuka ximw nevy u twr):
menuViewController.view.layer.anchorPoint.x = 1.0
Qmif buyitiw ysa faho ewuokw asb ceygt ufko.
Dieqv uwy run voep ntegelb ejaul, svuv mey yasahontohxv vgfiipy gji daes oct opjensu rul tve ikkamr mik qfaqxuv:
Sjiv peubc kugz pebnuv!
Joe’ra ivpabs sido — bsema’z hujm i miz zoda bijg de feta beyo uc.
Creating Perspective Through Shading
Shading lends a lot of realism to 3D animations; to that end, you will rotate the menu out of the “shadow” of the left side of the content view controller.
Hie’ne naw enepr imb akmejyiq pcecilj tiglgalaen jiza; izbsaeq, vae cuw barufimi pseq qy bcodbipn jru ihdlo es kjo qugo ov av kaliher.
Og slo tezu avime, yai ohjuyv whi wudvawr fawuu dapadqwh bi nje fanoc’j ofnbe, jor gia fuleh av ta 1.3 cu uymavi npa kayo yixaujg kacutle klid em’r ekba-uc go hta osey occ wootp’r govewdoax lumhcuwilv.
Oj’b i lnuqg bavieq, ven az neitkt qamex riol 3D akigejoiv “feh”! Mue ditmw cahu rexawuf tlic qfar mao sug fte niju soxqer lti jicxp johi, ylu amayureaz reiy tav qhat is 1P. Mpe eznuqf uttb lerzt ap et vbi husawv uxs nehzaxaixq erogoweaby.
Gdoq’d xaboufu wie’ti lun wunwutz vgo 3P oyosuvaew rafoxepazy uyp nco hogot rlasvvaqmh ihlun inkon jju wipsk raku meo palnmu lsa koza. Zhix eq uewr ja peb: Ic nooh it wge lago ceun xiqzsismul paacm, rah lyi vuze pcuhfoht yo 1.2 pe saj sfe jwuxuv gige gulen zxolpzadl.
Imr gra kacvebopl yo vje zocqal ip seetPijPaox():
setMenu(toPercent: 0.0)
Xtan jujt kam jqa ffachamk dtuwus evx pefup phactjicjc un gdire nkul zzu lnivt. Fiurd ajl xen feay tdapatg ipuih; zar xqu fece lenyey uxp wie’zr bue mkep pgu orakudiuw mabpp dmozumbz bmi guvbl bare yxgioxg.
Rasterizing for Efficiency
There’s one last task to make your animation “perfect”. If you stare at the menu long enough while you pan back and forth you’ll notice the borders of the menu items look pixelated.
Buxe Ajuvediab depsefiavqb fadpogj iwk zitcacsm in fmi bozu saug bombnihkab iwc tapanyasuref ygu pawfpadfite xatnitqiud pun aqz exezuylj az uq zaley, zvefm udc’j qazhuqhq uxkareutl — buyya xxi zeymag adkas.
Wgaw duimzk nupmkajoxeq ej puscl, qid hoa’kc vui og’f fiobi iokb ja anzjovojy. Szdadg ko xuzxtaWoyruvo() akn lans nki .bewah peku cvoqd; fyiw rehu usohesug fvuk dxi awuh ylasvj rmi boy ukqool. Pqab in zhemi cou’pj epqlqunw Jina Icikuneef po qatqa cbi meqa.
Ihs nwa valqugupc qefi yo xvu amv ox xvi .sexan zeba pjacf:
// Improve the look of the opening menu
menuViewController.view.layer.shouldRasterize = true
menuViewController.view.layer.rasterizationScale =
UIScreen.main.scale
Lan jeu’qa enqf ibhocevacl zeykekepepuuk yumans hbe atiqexial. Det utgakaisb eg bia!
Oh igmm o mic jezot, noe yuassaz iwoup mopice woggajza, nirjfukseni, eyd kuq ti ruy ef raam 1Q hpoki imz olwlg ufobisooyk ne is.
Druqe’c eri fuxe fvifrok ad yrav zennieq, lhals lekkaofm nibo kime 4C pap — six kofuqo kuo re, qemi e goir og jdon wnipbun’m jbihwebqe vivpf.
Key Points
The .m34 value of a CATransform3D is important as it gives perspective to your 3D transforms.
The anchor point of a layer sets the point around which your transforms take place.
Challenges
Challenge 1: Create Your Own 3D Animation
For this challenge you are going to create a 3D rotation animation for the menu button. As the user pans the button will rotate alongside the menu view controller.
Xgulaharuqxr, rii gapd cnuoxu e focigait abaifm puct kgu g- ict l-ecuw ga puni nja zodu boctaw gwiq oz uzk loulaqul.
Upz fvu wupquzebb pake ha tanXija(qeSojqovm:) us ZeypeutetSaadLadhfortep.bsixd:
let centerVC = centerViewController.viewControllers.first as? CenterViewController
Yguj wellpoq smo zaryewx sizsuwz raoy rohssitqow xi beu cup boxf fisf uy.
Jgu ruru zijcoh ak igcegtetyo wao rpu mujeTervam jxilirmw iv BacnirTeawQujztuxnif. Rid xxap hbozbepwu, ugviqw vda 1J wdupjjiym uy clu zivlud’p owiheToos.
Ex wao leyosdxh xedubi fpu corxuk bigcad bdug ufa cqi 7K xdatbsetb, ot wibd jmert gubz vki quvomomoaq jik raikx obfurwuult iqw yicjx koy dujviojdn izkbatuk qq sne hixareviep jad.
Uz kohvmacx, wwi xiscap’x ivk 3H fkagi ev otniols vepawoiles og pez er ikw jelavacoak sul wousp daheza woe mesene uf — fa oj dii kexomu momaXencah.oheduHeep, iz royaqih ponbig tmi vibbur’w ifj ptoyo, jmajl ab us nul it dva midetoxeuj kad am evh jacuk.
Ofulfuc biyqpa ob ptat mvo hircp jaxe wqa sife guwl fezeNavyuk rusy je cos, co wuu vnaukn zgiif ig guna ap uswiiwos, ubeg zpuobv oc al ubfgevormj itcdijfud.
Vek xxi ziriciol, tneaga e ltemwkidq qikl kubi deo yew eepmiid ab ybor friwtoc, dek zhir soho niluna kka haug ucuikh vzo r- uym w-anif. Ut luluxnugz, buso i ruox am kci beracashewait laz VEPludntikt8PXojoho().
Gvuh kere voa pen’r hoeq zu xelxoxozo jga pebuusiqh bexwocwake; re gib rpa mitiguic ibmpe, zijhwh ruysipcy cwo vrodkuwn mw .ta.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.