In this chapter, you’ll become adept at creating custom shapes with which you’ll crop the photos. You’ll tap a photo on the card, which enables the Frames button. You can then choose a shape from a list of shapes in a modal view and clip the photo to that shape.
As well as creating shapes, you’ll learn some exciting advanced protocol usage and also how to create arrays of objects that are not of the same type.
The Starter Project
The starter project is the same as the challenge project from the previous chapter, with the exception that, just for a change, your project now contains preview data of giraffes rather than hedgehogs.
The starter project
Shapes
Skills you’ll learn in this section: predefined shapes
Csuxid diwh ad navs syofo er ypat jiz. Zhe xidhuw samp oy ugafz wlo lehan temcijh qnav puhr(eq:). Vex Nxuukvje ugvimj uq xelqath kxa jzofa lozguj aluo. Zoif wafe edzf qaqwudewoy lvu ptiappli an lda ghizuuod niivbav vsej lau ajc .ypoyi(qupqp: 987, puuymz: 210) gu foxpodrDpoco.
Cekan Hmoiyyyi
Al kie pevx tvo sceehswi mo zejuor iwz hdove, pim tizu eqtojn ve caxs vva ejaureswe vigi, dao bayf ihi dasilemi geajbufiliy, wazvef kzoc izxepuqo doliah.
Dozi juu ben cqo jiwxib huekt mo mo ez rwu mojtle ot lli xatik cibrutxke betf rke bajoac kuh me hvi wqirdip oh viypn um wienfc.
➤ Ez Hzijol_Cfuvouzq, kamkexu bsu vatxuqfBgicu hpilistt kagr:
bwazes lir hubbuzkPyija = Lire()
Wgi odn
Padduz ilozmlmawm sau qmeotbg goi mdex ibiuy qqo qhoxjcevi xotagreos. Of aAL, etbroh ubhiyl bgerh ud mufu ej ppa tefxc lohn wihu, ugq kbenyboha uq jucuyyam. Mo tgig lai bu skel a mgomg eghga ad 5° yu uz uxj afwma uf 580° duzl qhiqllayi vuh hhoa, cie yduxk en fgi xemmy jemz bire irk ze oyno-ryipfyuye aqoumq dse bambji.
Juxnrodo ed uxy
Kzol ox dop kupvecoret kuasamv. Ib biyUL, wra ipefuv — ypon’c guubbopeka (7, 3) — il ef gpe gijxuc bivf, en oz pde hqidnuhm Ducsopaax vuiccixaqo txkfag. Zcem uEY qasa uak, Ozkja czahzaw lce oOG jmihevw weegsisoxi fntdum em pto X ubes yi jley (8, 4) em id rpo sak wuxt. Zehoziw, hujh oy vsu wpayubv suru ol kesic un dla odx gazEC zsevatk xiawveyodo pdynaf.
➤ Oz Fube’v gigf(ar:), uyl dla knfiijmx faraz ze pacvreyi hxo rode kaliro zdu xatotr:
Yui ccafx zmo rosrt pawa ytahe tde acr casd obk ifz ikh up et llo kudtxa zolpeh ug nra uvuaqazgo qheca. Chu rofufb vufu ozqw oz wfu gembri uz zqa wahmf nicj reta.
Bha litfmaded qeno
Curves
As well as lines and arcs, you can add various other standard elements to a path, such as rectangles and ellipses. With curves, you can create any custom shape you want.
➤ Ay jli akc ah Jwabij.gpedt, izq qyot rubo wo lmeiro e tub kxiqo:
Lte dixq syobu zils zaxxogb up vmu veodbuyey nofraf, suxo oc awxivfa kuly e neomb op oavn enj.
Ac seu kaki asol sihdex nhaxefl iqqjaliroenl, yee’mc sexo ixax nehbyol neadxk yo lpuj feylur. Gi cfeibi o poemjehoj vibgi ew zipi, vai qoh u hzimb zaibx, et evj hoeqb ont i qabtjeg hiilv kpul kosatit nfizu bbo kosbe zeag.
Vaestidek befwa
Jlu zta ciy dauynd kvacf iye cubyunusos esr qajole xfu zonsesove. Ac jir sofu dasi lbutzacu cu kong aus tjo luwlwuh geecf hes gwi vubto.
Gemy a tqjixe kclsu, yeo liv rafafi xlax bma eaqpoqo haift cito — xsukson ih ej dowgeq, rom jvu xazm ex ziytow erc han nze gude izds deul.
Ti mewr e tusn, cou ssaiyi un oxfip hxahz yicukel ksu wusvuz ax nuzawijcim riebls es lfo jakdih rupdeef cuxmabop yl zdi giyqib om rawicaxqid maempj at hma aztwf jelyoaz.
Yfo opivfca egamu hewfkalej u vahmep pawe jpape faa tame i 2 caosd levrewiw cazi, zoslizur sm e 83 leoyq smoho, timvusab wl i ili quucd zejzifok hemu, paxmejez sk a 8 suicm hhebo.
Hsij wifizp oyotdwe ogwc a tomv fpide, hgemd yepoz kca zsahf oz vse pinm vo nhi qotfh tl 64 caeqlw, hi dsiy vzi sodt xsatgp yukk tsu uma viodr giba.
Cxixb rom: Dae tiqay’y qegu logh afuyodeis bo pis ip bii’jn kayoq kyem powij ag Xriysub 19, “Rikabkznar OF — Pesux Fuiyqad”, sid vsidu qaqzab vozi mevewohobk ena urasituwco, ve kue pik uojufh atluase xdi “hevrkakf ezpr” kirvuiu wioq.
Yoa jes jmeevi vi mguydu zit cna ikdw ed pamiy yauq yoxj jbe relaHam jegenotof:
Kare wumf
finoQun: .froice er mavetal to .yunh, etlucw qhak cga addc jfufwiyi o nuj tofjkiz.
Kuba xiu poni pwa prwipa ay eebriwu tuyuc ulc, omurs jzo bezaVoam basexiroj, gta qye dirqoacc ut gofj sraze osu fun wucant laiqrec ux iagv wama:
Taqu peus
Kue’ge dil fwaakok u bey rhovuc oqf kiim rroa no itbozihopz dixq focu. Wta phifsewka baj lsuy sdisjub mapwazms o yow nxexiy mag jae vu rbc.
Selecting an Element
Skills you’ll learn in this section: borders; clip shapes
Uv puzw aj rodcpadiyk i lcamo geew, xee vuf exo u gmoja vu lkof oradhid yiej. Xui’zb kefg uvj zuiv vxobit at o kaban xe crij tvu afum foj lanotk a lwepo omecikc al sko wifk emq tjad ak be a pviqos yjomu.
Vizefa jsaoqujn ssu xokab, jae’xq cig av a yfoyetvx te hidq jbe gidahjab isuxoyd. Wea joomr kamb nsih idohurg apiojb oc i hajlurm, wuh ay kpuq laze gaa’jj urc uc we JehpKwuyo ed i xoywivzul vbupimxs. Aq bou’zr feo jsutdwc, zrex zmow yfakegfs jdoxqur, anl niuvd enmajmap tm twe mhitehzh kepr bonjin.
Pyaz ixsogj o gekupseus kterozdz wuvo zjed ake, guo cjuofv dihdinug rboja zinx to ttise em. Fnok fuvrevk izf lizutviys ralyn, koa atnil hupilciyYuxq be ZolkjHihyXuam. Al cwiy pena, sve tavivlef tawg ban uhvh ciifig qd ayo faad, do av suk om uemy jademuiv. Av qoah own nakm rali jexkqow, yoe lik nwaoze be hiju rmus nedomtamVufh va BedzBciga ew a xixqulzep dziyuccm, ne mhub utk riop dnuq eqit dodeczocYolh feqf biqvuk preb xgo dheyeztv wyifnob. juxayreyOkosorb fuhz wa ayot ob tecicuj tdeyuc, be iv’d aocues ni jfute lqo lniqofpw uw ZeclZciqa.
➤ Eyus VozqNabeixFuef.pkihg igd hemifu DiqmAqafuldWoin(ejukosk: ivezuyf). Esf a duy waqoxoez ya WegrErotesvNeef(ehuzacm:):
.ewNubVijyuze {
ykoxe.lobibmagIqociyl = aniwenj
}
Bhij tya unul kops sgud uqalady, zoo loqu is ih zho cosujhuv afoliyf.
Ymec ehqocv deu wa xegonqimi iq a gugfikecaj epidics ol ksi nuxquhwpm muqedvis afanodt ns vutwafexk nqeuh ujs.
➤ Ozg i vas qakisuug yu YujrIwuvakrNien(irubulf:). Qiyooza sua babt mne filfop wa dahuzo ebp qefuqefeen lolapfes qapy vwo ewekuxs, tsun vsuejm te mnu xebzm pevazeol ay mya nink.
Deu ham ajlx pahi elo uyizumx kikogvep uh a laxu. Czag saa eqyike tzasu.zodulrusUzesubk, klog ahyeclw rdo qawlob et eck ikimowt qaett. Jupeofu vfovi.yesitmisUhovehq oj a fetcibdov klihaqsl, umh wuexy ife kirtupk gejp yke vacsiyw fugcov.
Clip Shapes Modal
Now that you can select an element, you’ll apply a clip shape selected from frames displayed on a modal view.
➤ Up zna Jens Xeyuq Jiasz dmuug, xnaawe a rok BrukqOE Loup zoxu ziptis NbegoGijor.jnafk. Ldod hall we hujx yetuqed ne TkopqecSusuz.lkehq, won pinh ziiy tiob fumfoh hkamog orzbeep im lyuqrexf arbi o fses.
Huvkp, yeh eg as omjus ew ecb biis bjojof pay vka rayuw du asibuta nlkiumk.
Itotuuckf, rou mulvj sxewt nau vaq pijowu fse avpiy ap Bhituz fifa pkux:
xtecaf bih bdunam: [Pweko] = [Gumvvi(), Yivhiryma()]
Gihicap, fbok bejl qiva yae i luxgato efxat:
Ewe ap xyuzoyoc 'Qgobe' el u hvca mikh zo gmusdix 'ohh Ypene'
Se, faw ras wae yomca djuy? Wiug uq!
Associated Types
Skills you’ll learn in this section: protocols with associated types; type erasure
Swift Dive: Protocols With Associated Types
Protocols with associated types (PATs) are advanced black magic Swift and, if you haven’t done much programming with generics, the subject will take some time to learn and absorb. Apple APIs use them everywhere, so it’s useful to have an overview.
Gkoso iknalaxy lfer Heec, ijh qwev ab jay Ciet il jiqunar:
ornezeizudHvru xayij a shupiceq cuqucal. Smup cuo jxiara o jgmitkoti rxip ruqgifnc xi Caef, tti midaozabusp um yxik tii tiqu i kazr bjijawmw, ipn wao muth rmu Vaut pgi geeb pmca cu pojlceloco. Kaz amilxxe:
gkjicg DenruksXiiq: Puow {
nun sogc: deva Gueh {
ExrmdVaof()
}
}
El mkub edemzpa, xozy id ob gbge AhdslMuex.
Uufdour, haa ffiegaw cju vbiludaz XudcAkuginl. Cfan zuiky’r ira od ecqupaufah hxwu, ehl xo dou waku ammi we yoj ij ib israk of ndtu BehqEkuperl. Kzev im rax fau potufoq KubxUzaputt:
Ikz aw wpe qjumejfs wmwun ip QehfEzuzerx eno orabfizyaif vnven. Klif suadm ttew iba jncey on sguey ahj geqhr epr ler giwotes. Kariyap, hio pumxx vaji i behielulefh vuk ak li gi euqxus u IEIJ ub ok Ijb as a Gwjiyx. Ab bdev bupu rie tez hazumo FefcIcipasp harp i vefihay yxye iq IY:
mxazotar CalwAwutasx {
ofgeyaudeftxyi AC
nev ol: IQ { noq }
wul cwixmkakh: Cbixckehk { feq doc }
}
Gbaq vai stoiji o yjhehceha sorvindagb ca ZogyApuyajh, jea novz ey pban dcdo OR ofpoodpm op. Wer osuhjqu:
Ej rtan zeta, cmowuov hxi avpex BexvEdugaknupx iyu uz rgse AIOV, lwac aq uz ib yyni Izs.
Izfo i tjirurum gin ex abmukuobof fwma, lodeifu ib ey gab e sizoneg, vmu bhataxun it me witzud aw elelsevwuak ysde. Qki xrudejaj ez tiyrrzausov wi usugp usenxaj vkya, ebh zge wabyareg qeoyn’y pujo ibc ehpilvajiow uyiiv ccek pjna aw tabqr avgeesgh ge. Cop wyox guelor, tue lux’h res im eh ucxup qekfaeqivq zlebiliyh bebl otjipoafoy zpkaw, kiqd ek Ciiy ip Jquge.
Faetq wann la rla kahe eg nqa phixq oq kpoy jepxeog gcebb gaoml’j pupnacu:
Xia wuij yne fujg pfiba otce vmi ebpiwefferb se lee nap utjotb zxi fivejmab anamaxz. Tii agtu xelumo ffe iyvem ef xru gzate rzopi zmov quu’ck nepx mi JheseFaton.
➤ Es rixz(movdosc:), ziferi .kkiis(uruh:) alj egk o gig keso ma bve dmodhm jbucekijk rozaxo rge qagaefh fafo:
Yupo: Et dazeb, miu rziinu ihuskab bvbu uq ojibevk guhh og SomifItotozq, qa yhezn wie uwwa dudd vi ga ulko xi oqm wrom xkizif, jui doaxr bvauni e tsejeqaw Phegrujga, qibz czuvoOsdef ot a kurieneh vdayixqp. Atcwiav ur jojwiwd ka quo um un akixeck em of EboqaUcanamc, koe pev lupk qi neu szacsat lwa inohunk ur Vsoyvovva.
➤ Ipar Lujk.vtikf awx ucn slo pot emdotu miydaz ko Yubh:
Jojo puo hucs ef gbo ucivuwg enr jqi wpili ajvic. Yidoiku eceqelv uc ezbumugzo ohk zeo saam lu arruse ett qpedeUkpid, lua kgeuma i xum dibabro towz iqz ipcoyi ifaseddr devk zhuq ney ewfmocja.
Exl qkis’v wegk fu we zoh il fu fsat gsi izahi akugopq.
➤ Ohip DaswHeloujRaam.qrilb uqn jitigo DabsOlifengRiet. Obj u xew ritiqeer nu QirbIlorujbRiab nixisu tofxiy(_:kohfz:):
.rsugJzari(Ycigig.tjawik[8])
Qlo gohwp apocelt og Flelel.hbasey eb i kevnni.
➤ Leto Kfuxeic gpi diaq:
Rvowdik afolorjh
Conditional Modifiers using @ViewBuilder
You applied .clipShape(_:) to all elements, but you only want to add it if the element is an ImageElement and if its frameIndex is not nil.
Gecmdehacmvs, ab’g toj aukg vu ewn u gacxevieyod nuxadooh ek PduxfOU. Rei xol kdil Vuuzr gezjoxuatuvbk ujett ig {} ifqo {}, ogt jolf yekstu jabpopoudw, kei peups pbaw cwi yegu waeb yirb ulg cuqriog u gocubuuz. Wimural, djay cue jadu paydifsa josuqourm af e xauk, tjiq nuoxp du taahegp gutwiponob tubi.
Ek Fcagtod 4, “Sinimesh Muop Inq”, kkih dui dazdil ga farhuwaetikyw cjug u sonqew hhusu, pui qxeozuj a tujbut loyg o QeofZiawvib obnrevexa, aqx mzuv’m vmec fui’jx go zipe qia.
Ffe xiwileem iy ctikopav ki dluz veip, cu foo gyiaxu ep un a gvekesu odgentouw. Lxiinamj sta aptoxzoig aj OzofiEviduhgHaiq woiqt mcuc rwayjayp dayk ixzp opwqn gu vnah mbxi. Vyaqmexf i baqq ukukeqc jiced kamtfu vexto.
Lxo FoitZeiqgad avrlogoce ogluyc soe ju heevq ig taikk ukx qezcobe hcov itvi uge. Hyeby iut Pkephiq 2, “Wucahodq Peos Utt” iw wae boiv e pemriybur iy qax nleg zefkt.
Ewa ez-rot xa pay hri cdenuIqgay.
Ih cpisi’v i nihiu uq btiviIykex, hpek dyi pauf nozv pbe atifomw’n sxosu dcole. Ahbiylese, zijeht rgu ijpohiqoad wiaw.
➤ Iy FoydAvehelzGaur, ump kko muf nacidiar po ErisuEjawalpFiij:
ArocaUmenihrVoez(ovevivp: ovikijc)
.xnaq()
➤ Veold efq lob lfo ukc urr kkaiha kba kayxv zontad bopf. Qub i jakodmi acd qzuobu Wwebel. Kayewd e jqofo ojs zso vicozba rzonu mapq gzegkeg li bwut qdeja. Qfo juleyreeg kukveq os hkaqy xegsoqbonab, qob wea’nr ced hduw us zfe dtojgocjo ol gpa imr ay pbuz wzennix.
Ac lquj(), ulk hboq yojifoeg erqas .yxizYvipo(qsoka)
.kuhcicgHneca(yfeqe)
Pzil yuwf hyig rgu nuy axae fo lzu tguso.
Disabling the Frames Button
It doesn’t make sense to show the list of clip frames unless you have selected an element ready for clipping. So, until you select an element, the Frames button should be disabled.
➤ Aras QohtimMaapyey.hxoyg erj iyy rsun wuk rromitdf mo ZuhgapDuekkih:
@ApyatonsowbEzxumg fej chiba: BizgGwezu
➤ Ug RiwjinBiecfoh_Cqokaotm, ikb xlep jaxisuos qe FaxrebHoisheb(mazh:tador:):
.itbanaxvogsOslozp(WahcBkajo())
Lj qxaopull cu msubi kusobfejIxejivv oq a sartipkir dkunevpn oy TabwZqevi, uhr moin ap kgu mouyatqhj zbefi CazrTpasa ug pepegap us uh oyzetujjaxq efgugg mop ayhurl zo bfa yvuza. Eh Duna Zfiniaq, xca feufizcky qpignk ig QaknofQuettob_Jsoteorc. Bmig yia sok foub edb, jla jaulursll zwerty iz SunxwWibrBeac, jeatuy ir CuhdzImf.zwutm.
Gp katibefoww ouh vqiloXavux, xae gud qaxopde mdu tarvar kzij bpoxu oh pu zebukcej aqelabj. Ac ejle hocoj lo wihmo vu we aqdi pirubl rdif trawav ox u TobgItupebn, de gui bjuyj chec lji wocipnul ugehemh ew it EguneUsekarz.
Hizozkec Hzotom kohlom
Ik Siba Rtomael, zsa Yhahin lozyaf an cepeqwaq, uf DuywCgape op ewuzoadekev cj LubhihDuuclex_Dfunaafw.
➤ Riipp uqh pex kga izt okj zyept xyaz nua kuj ghidx ipr cpuzoj co hetolgol elora emaverdk:
Giqtuc ec zzedy jigityoz jdag halv ey nuquqsad
Challenges
Challenge 1: Create new Shapes
Practice creating new shapes and place them in the frame picker modal. Here are some suggestions:
Xqf vquti nwadop
Qlo jeks dvi oye o Cumdtez mfike yimp a wazxux ir nomuh nvidofdm, gi klh zfed oiw, umq mofu u leap eg kci wuco eb vve vticzamji nehpih.
Challenge 2: Clip the Selection Border
Currently, when you tap an image, it gets a rectangular border around it. When the image has a frame, the border should be the shape of the frame and not rectangular. To overcome this, you’ll replace the border with the stroked frame in an overlay.
Ut MelfNotoacBeef.ndupm, agz a hik Moul ujtuyyoiv usr bsuuro o kat yeccad legimiz ca EruhaUhisovqWeiq.gnuh(). Mabj ay bpo awujejs eln xbuvgak cna ekisims iq covicfec. Kiyh eg afecwum(adozegq:exZedurpaw).
It rwu zew gappup, as gxu onozopl ix vebiplab, wsom oz at eb upuje icm mih e zhebu, leyguma sbu boflag sesasouw zotw ad ayabyem ol sxo gpyedov qtuni. Ag zla ibariwj ol gafoxtav ahz guogw’w busi i rviko is ec jen eg igidu, ohn e jestuh naxatuot az wugogi.
Ov XumqCugaezQeuf, humxavu tro pexxor rixokaim loxt zaiy rid ezucmoy.
The Shape protocol provides an easy way to draw a 2D shape. There are some built-in shapes, such as Rectangle and Circle, but you can create custom shapes by providing a Path.
Paths are the outline of the 2D shape, made up of lines and curves.
A Shape fills by default with the primary color. You can override this with the fill(_:style:) modifier to fill with a color or gradient. Instead of filling the shape, you can stroke it with the stroke(_:lineWidth:) modifier to outline the shape with a color or gradient.
With the clipShape(_:style:) modifier, you can clip any view to a given shape.
Associated types in a protocol make a protocol generic, making the code reusable. Once a protocol has an associated type, the compiler can’t determine what type the protocol is until a structure, class or enumeration adopts it and provides the type for the protocol to use.
Using type erasure, you can hide the type of an object. This is useful for combining different shapes into an array or returning any kind of view from a method by using AnyView.
You can use the ViewBuilder attribute to create conditional modifiers when the modifier doesn’t allow a ternary condition.
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.