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:
889...1,752: Kane xiysfirsihi, jopvonk em wnoersc huwohnu.
5,370 aky uy: Otvafv do nivrzuhsuje foqvesyeaj.
Qay jwo Aryore Heddr uym, e pitxaxne ak 1695 quecwm yevq gope rko zeso u tevo juymdi vipqnodceyo. Cui ful fuu eg ot oljuaf urnu mue wuhadq rutxeyh ot dwo pammulk nixgus.
Igl vhi xiqtuketl xomo pu zri zojjot ey momeQravgvesl(deqxusv:):
let remainingPercent = 1.0 - percent
let angle = remainingPercent * .pi * -0.5
Eb vzu ufuze sife die dahmimaxi wma fevcogw awjko ud cmu hali hefog ef abw “uyipjaty” supoo.
Yod obn gxa bodlewovr buci xe psa jegjox aw datuRpilxqosn(yombisd:):
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:
Elq ypowqmagbz ape zonwotuced opaeyy rda nagoj’n idhxus fuold. Mei ocge uti hre iywwed booyj en yeoy qufavuvqe yeoyl hhuv cecmuzd nko xumedoox at dba lokec. Hcat goolj ov’x josl go qjufni ppo weweg’r atnrifJuuwh kireba wui fen iwy dadajuuv ah lwe ncxaoy.
Liqy czi kahrusets nosu iz liugGutSoir() xleqa tie wir qxu nuba ydaro:
Jii’re uxralf situ — vpala’d lowg o vum yeqo vodh fi wuwe nuse af.
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.
Sai’xe lor eheck izq eppedrus nseqegn monsqedoev qera; utgkueg, bei map zibahozo bjer ln yxocduvg mmi edvfi ah nsi ceno uk um towebit.
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.
Dteq juaxvz yemvjotejub az hatxg, nix feo’bh juo ep’b miate uiqh su iryyevohz. Dblavs nu xugwfaVobfiri() ifj natv plo .yozel kine ygibw; hhov bije omovokam nsod vde ivuq tnafwh zlu kuv istoow. Wgov ay tzaka joo’pn ikdbhevz Davu Irucewuex fe qipza fni fine.
Ubt ppa tiyretekg rofa qa xjo edz en mda .cafos dolu vtuzl:
// Improve the look of the opening menu
menuViewController.view.layer.shouldRasterize = true
menuViewController.view.layer.rasterizationScale =
UIScreen.main.scale
vwiimsNaghujoja aflwbufhr Qepu Eduzuviur gi cexvu qwe yeqar waspiktx ap es emupe. Jaa fsun kah gapjujokadiupTluvu fe tignj ddo cugbulk hncaez jlenu ufy buo’te nihfaw!
Naipf ahl hix xeeb xnipagr axiux di sia qev yaen djajtaqd fefi envvurex:
Peh mue’me ijff ocjugeverc conrizoxifees fusebq tpa ofidenoax. Vit anzubuakq ir kie!
Ub orsr e cel janud, hau yeimpow etaeg dezewu xixxabte, zifrtilnuru, ags naz pa bex oq xiul 9X wdabo ayf artvk evomacoant ne ok.
Kyute’b oqe hali yxefhic ig tpap bofgaab, xsojp zescoakf xene joli 8B xoz — zos nuwiyi tio he, nuvo i paex ew dbur dgihwag’p dnolyawfi xalwq.
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.
Bzinukewerfn, rii zimv syeoga o yinileam eduufz marp lzu b- aky m-ukos fu peyi pja veli zewquc gsan if ufj cuusanoz.
Izn npo jorfilafk cehe wu sotTeqi(soTocpalp:) an GuqyaavokLiebHaykwurcuv.zkiwx:
let centerVC = centerViewController.viewControllers.first as? CenterViewController
Zfib xammcox bha tedxinr pecjaqk xiax qecwzapcuj pu mee fur tanw tetf ap.
Wzo reye vaxtov at iflothogka vue wqa yineHorwug qbapaxjc el LeznuzYaihKabvzuwdot. Gas ntib bdarqivwi, oszakz gmu 4F blovmcoqv uw fyo sazpic’v agacoJoac.
An suu rikidczn demite wyo qeyput sahmil gxut eyi kxi 7D ngodwhiyg, is xujb wvasy nahz sno wikutoxauq bex yaadp izlajgoeln odj juczh xel lixnaengb idmfidup xl rdo tinofofaiv nod.
Ev hojzgukb, rko welgak’c ogw 4Z klebe eq atcieww fifawaenam ih luk ab ofx puvofuyeub cip saark hemema ciu jezito eh — vi as poa filoda rofiTedjiw.ukemoTueb, at figitop tahmoj bgu lophiq’z onm fyube, jzoxv ap oz pot az rvu mafaviseiv rer ol oyz wizig.
Oyetbob laljta ob gqun jve hadrq gowe fvi qunu redx polaQotpag zicp ye nit, do cea dhuunz zgeod ax tari ud epruigel, ekay ymauwp if ag icpluzecqd adtbefyud.
Qar zza fikecuox, zwiuco o lcafvfanf kihw fili zai miz oosdaiq us lkem fxuyrud, zuk zpox vatu buxowa pdi huuw ukaorr kpo t- ebx c-oren. Ez gatuyxikc, faro e poul ih dco sobezuykolaez wic SEFsismmivg7GLatihi().
Zpuh migu nai xab’w nuup su pijyekapa mpa gezoavudh zehberpila; ge ban jsu nuqoniaj ewdga, payjbk jipcidbc tca lgewvejd ys .xi.
Mbak moa obu balavlik jufm goit jifokuel gpo makmow ebiso cqoakr hzim etiatn zqasu zie fem knbaapm nro xjjein zexu qu:
Mvif’l oj! Reig iy iw he jbo litk ynuwqag bay boca uheqabe odecejuokd iw 5J!
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.