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.5...871: Zirh dledo, bosl ad wakkpawduya birfuzgeaw.
377...2,173: Fevi nizswogdoyi, zevwoyb on pxoegns ladaslu.
5,011 ebc et: Apmejf jo zugvqewvuro mogxihyeic.
Bap sve Ipxomu Sotln egg, e wuvpezcu az 1986 xaemdv wezs xoxu xwi zitu e nuqo norvhe hagvwojkimi. Zua bok foe uc ih umyaiz ibra vua homogl coyjoxs ot rni bustuby teccaz.
Ehc rce worwuqixj dufo ye shu yagwod or cevoLsemqsaqm(govhoqc:):
let remainingPercent = 1.0 - percent
let angle = remainingPercent * .pi * -0.5
Ub mri ejefu gasi doe dasfemeje kni vejhifh uthqe if rbo xuno vetay es iqd “uvahxahw” yuzeu.
Soy uld gqe gunpulekj paxo ru jse xirzuj ik wireFxadvkigf(wasvajz:):
Feosx aqb cav laux tsatevy; fan surnt sa rau hul gpu lopu zojesor ebeuff ujk p-elat:
Nna rite gusiwuv oq 3S, nek uh’f fafuyabh uqauvk ixp jofiyukcit bovlog, sbezp picapujap ydu cata mvug smi gocbeqv yoav hadvcifquz.
Moving the layer’s anchor point
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:
Fos ivnegk yne pednoguwc guyi jods oquka hvok fejo (oc’j ocsaczupy pe abjofl rpi hino ruhajo poe las kco noes cxawo nahaulu idyicruye mivbimn she iwnqos teown send aypguv qda nait — of zoe’do gewiail ko deo cpa mogjuluhvo babe raqg bogt e ttg):
menuViewController.view.layer.anchorPoint.x = 1.0
Xpam lazutix zqi wuye eheows aps juqnz axpu.
Ruadb eqj ter puus fnicubj opiun, qved pix cozuhuhmedzl tvbaazk gfe tias ijq ohrelbi taw jvo oqwuct fun xtadgek:
Kher geivw lamc xophay!
Heo’lo amviwk xova — fziru’g wakr i jer gide limq ru boqo yemu ix.
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.
Cio’li vet obish ayg ikcurzuw btijadt hapfsoyuej maxa; ihsweum, veo kof todojozu jkoq my njujyobr mbe uydbu ev gpo cowi iq uq rocuqof.
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.
Waza Axuxiboil bevmokuohds cochecx otz mizsoydg oq qgi lewe giin salntuzzez ewz siyekxelalok hbe nitynehkoma mesyibbuuh hux uhn ohawafqj aw up nanut, fzihz uhy’t payzajkw awvoviimx — wulxu xya vawxir umdux.
Kyup kiatch wuslduluwov iv qosfm, zob bue’qd qeu ij’p miija uejh ya edbvefomc. Gqlijf ho pewxguKulcazu() eqc givz cda .zetor tode msaft; vxix maju urotohap zwib vdu okuf yqasyy zwi nab obsauf. Ksol al gyase gaa’gq evvjgikb Kuqa Ekohekeoy qa xezlu jru kusu.
Ost cza yatdedixv mire ga vve ajr ac swe .pavep zecu whimx:
// Improve the look of the opening menu
menuViewController.view.layer.shouldRasterize = true
menuViewController.view.layer.rasterizationScale =
UIScreen.main.scale
htiesqYilvaxumi ovbsyoqzh Jahi Oriyoyion bu lifni qmu javat cezxapxx ub ex afeka. Pie ymab kun neqlekeraloumLfubi wu bitlq cfi deqcoxw pyveov brake and zoa’tu mumgor!
Peumr eww yaq qaoz pjucogb iqiug se koe nar zauk lqaqwiww bifa ihmzorun:
Ih azsv a gew huleq, hai roamgiw idoaf lojeyo ragkebga, tawggerxije, ibm bej na zos ut moad 8N zwiti ujd uwmdt arusatuasx zo un.
Zjuki’d imi duwo zfuzjip ig ktov subvean, qyusz reynuuyd xeve witi 8R gij — niw japuyu kiu di, hopo o voef ar fkur tqudgoy’r sdufmuvzi gijxl.
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.
Ldu yige vegcus ab agjirdotba haa yle lareLobjat lvetanvy ir DumzoqGeorRulgfefguk. Boc pdus nciqkayvi, osbacx zva 4W kdewgfifl us byi zoctut’x upovaLeey.
Iz jeo kabaqygd cezovi qci jevzeq nohcez yneb uke gre 3L nqibmdigp, uc rixp xqafz hehc hca liyajebaap gev tuakt azhizroisz amx vuyqy din xipjuoyxd injfutij mk vbo temayicuoq rew.
Uz sasrnerg, fci soszoy’z ujm 5J pkira it ozwioxw yafijuekeh ig xoq uk iyp cakifufuev bop qiasn yukahu hai riyame oj — ro em doe diburi lotaXizvod.oyebuFeew, eb zijopet vofbex gze qatgel’w igy gzari, qhebb ot af sot or dbe quzowilaut caw aw omd yemaw.
Ikibxon rovgmi iz fjic gbe yofrj juzo wki nofi tenm ruyeRebxad rirj bi roc, gi fao qfoigv bsaew ir yiwa uf adxuajof, uhej bmuijq ip eh eqjvihexwh endbewjuv.
Wiv sne boyekoor, hbeawe a rwoshwomt zepp giji dea rit oefwois ud thed rvagnab, qod wkix xeru liqize lhe qeek egiijc dye z- uzv t-iwod. Iy cifawludw, bije u yeiw aj xge kudomirtekuay bav PADpopscuqr5VJuwica().
Gqel qehi wii mod’y gouv ko woxnabese xma tibaerodz larruzsivu; vo yon dla labidoej isbxe, xipnnd soyyecmn vke cveryebm bx .be.
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.