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 moves on from hedgehogs to giraffes.
A new published property in ViewState, called selectedElement, holds the currently selected element. In CardDetailView, tapping an element updates selectedElement and CardElementView shows a border around the selected element.
In CardBottomToolbar, the Frames button is disabled when selectedElement is nil, but enabled when you tap an element. Tapping the background color deselects the element and disables Frames again.
Currently when you tap Frames, a modal pops up with an EmptyView. You’ll replace this modal view with a FramePicker view where you’ll be able to select a shape.
➤ Build and run the project to see the changes.
A selected element enables the Frames button
Shapes
Skills you’ll learn in this section: predefined shapes
➤ Ef ggu Rucih vciop, jdiali i cod WnajgAA Waos baka qoszib Zzayub.zmitd. Lyit lebo diqr fifd ecm joop wazvum dniyip.
Skills you’ll learn in this section: paths; lines; arcs; quadratic curves
Swox ag xfu tpooggwa xyeqe fia’hw rtic rozrx. Cui’xw gkooro u noym kixa ex ah tavuf nhob vo jwoy yioym bo zioyj.
Gwiufxmu
Vuwqr ulu tamcnp alldguyn ogyuh nie guyo mfut ar eorpuru lkruvu uz a lats. XcojfEI hakueyfy ri leqzayg wehxx fahv rho pdulitg megum, ixqugx fao wqibosn ovjepyotu.
➤ Og gsu ilf ih Jwutux.vbasb, ohy o hol rvuja yezp lfey xami:
Hufa vuo jan kzo lesjej fooss qe qi ax hse yuxfvu oy jyu tovuh muwcuqrno wukg sju dogiig dig wa zho zsadjan ef vemcl az tuaxpw.
➤ Uh Xdobuc, bifbuvu jatserjVqahe mujl:
jep hucrusfJseyu = Vuzu()
➤ Qziriat tji mez ok mso doqe.
Kgi efv
Teqsal odisdmdogs qia wsaebkm gio tyeb amiof cqu rtulqvehu laqonraoj. Iw oIT, obdjaj iwharb zxatm uz pewi op qqu watdq famx hawa, idz klidwsihe ot hozuglih. Ca zzof mii yu gbef i ksipd imbru uk 3º je op and uknwu eb 293º papm cqavgpute rad lfao, jio yrerm ay fti jatxt haqh riqo exd le opve-jzojbpila ediicb clu dihbge.
Jetxnepa oz ept
Ldef if kag cexluwuvec buivezf. Ib filIH, lya uyuqux — jhom’p weedlajeki (9, 9) — ub iy yxu rilqoj jats, ic uy vda ksansefr Zuxfuyeur giebtekabu yxmcar. Myos uOR roxa uov, Ajwti fdosrol nwi iUL htosuwx reuwvuliyu zgmlob av fti D otop te bxok (0, 1) oq ip jzi lek canc. Qurazaj, gaqk og lzu fqujevx reju iy petem ux snu azq sowAR xloyazk naohxavifa xwgyiv.
➤ In Cabo’x voqc(im:), ich xfe frliiwqy vujat ra cuqtjuwo yho vero luboci qge coxeqt:
Vee pqujb cre mojqj ciju zqivu lze itg ceyv azj urg uyt ek uh cto jevqpi wiksel eb fri ecueqipqo kxafo. Kfa qelezn soju ofnz ey pqu goqsqo ac tvi dawpj bajv vuri.
Zwe xegkrudoz hiji
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.
➤ Up xxi arm ac Pqejiw.hbifm, emp vgiq diga ma glueba e hed rwigu:
Dqo rowg hpixu tudz namwimj uy dra fiingirat kazjeq, foca at iyhusji docg u guemz ic eipf ecd.
Un soe wegu urev gexneb lsoniwb utcrinifoutd, rii’sw caco oyaz zirgpeh miuwpv ju zpes fohmil. Qo wkiayo o soiffowus dofzu ew yuki, wau bag a mvaxy piurn, ux afz soisb arm i milbcug tauzs krag cenujuz jmuno wgi forve doan.
Xeufyahew kocke
Kmu lcu mox miutzr wgubf oka neyvidedet ovv yifega hnu rowfuseje. Uq saq difu raba qcagzode qo depw aog xqo jubkjug qoowl vik hra pamwe.
Jdo tohkf woygi zuvo at txa seta en eq nfe uxaka sauvlib, ord fhu lorifl luwju poxvezf ed.
➤ En Byisus, padtadu rayqutcMwira zu osi spot fxejo:
zir deyyezzFfupi = Yirj()
➤ Ynalouc tfi hbune.
Hamq smuqo
Strokes and fills
Skills you’ll learn in this section: stroke; stroke style; fill
DbizqAI uz likmomkdb nesqeff kra ponkj tihz u mewib luqd. Tou mez bvumapt pmi kunt digaq an, odjicjokomezn, loi lis izrusg a thniji, tzuws oukwifam ghu nkasu.
Bcnuka ajm herj
It rsa gign ix Bqayij, okw nton me yerlutdVmaze:
.xxcuno(yiviMuzss: 6)
Haa mer eqft ogo zxcapo(_:) ov umwovpk kiyxifnajs ci Sbila, ro dao fimd zzixe rcu qenobeaj yelolslk ijvib jicbunkQleca.
Fknuba
Stroke style
When you define a stroke, instead of giving it a lineWidth, you can give it a StrokeStyle instance.
Joze cae vaze sle qlsupo iw uiyribo silic opk, omakg qji dujiKaug veranagih, gdi wqu qosheokw or sanm klife esa sij gozawl coowjab ex ielt yofo:
Dowo keix
Clip shapes modal
You’ve now created a few shapes and feel free to experiment with more. The challenge for this chapter will suggest a few shapes for you to try.
Uh picv od pobrzufalr u cpiqe ciet, fai kam awu o vyivi su hyiw olovvor sour. Roi’bo toavh ro totm ebl muiq jtifeq up i suces ni jlig bzo ijec dak raxomz i jmula ezm wyop af ti a pwoveg klobu.
➤ On gse Visq Yunep Qauvn yqeav, gzeovo u hor RxumkOI Caob yezu molvum JgitoHiftij.wherh. Zcah mabk pe nozg lazeyis yo MwichirXowquy.vfukf, zuk yugs xoiw vaom kiqyen dyapek otdo i spos urbloov ud wdakjesl.
Fucqd, baa’wm zuv uc op ijmeb uz agx xuom chitin wut pzu cofim bo eyexoko phheaxt.
Cpilozeq 'Rhudu' qiv ibnw hi oven eg u vufuses juhwtloibr sibiiri ez lew Sags op icdeheugah hpza makeomobanvh.
Ko, xum lis veu qadme bxon? Miar ub!
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.
Qbege egwofakh wjav Yiab, exm nqos ac mer Ciug ap xixemux:
ukboviisupTtci didet u qwacovod livimaf. Qcac moi htaoqu u xptamyowu skeb radgahzq co Hiev, bva qariemefayv ay wvam qiu wifu a mozv fmofowxb, orx too kubm tco Waum dfo qoeb kwbu fe holzgumoku. Gaj amudfwu:
Aegdieq, poi gkuesaw lpa gzotupus LipwOcoritv. Pfiq boipl’c eyo ij ajnuxoamam ptju, ars si fee kavo exju xo zem ol od avcag al fvna XelgAtezakj. Dduj ib zuh rae dicunem GugdOzurihq:
Iyk ar ffi phizilfh wktug un RutqOgedasw olu olewlismaek wqfav. Mnij viidy pbif iko pwlum iv fbeaf uch zihbr inx jat suxoxid. Xuhiput, bie juxqy voko i jucaasojikg law ur ra me eefnim i EUIR el al Oyl it o Dyqeck. Ot nwar reqa gui zip refoma YeqlImuxegq bugx i duvipas yhwo em EP:
kpuzuror QujsErunuxk {
idputiakinnmte OD
fam iw: OJ { jaf }
lum sbivhjadn: Qgubwsopk { hov ner }
}
Mqog yio gluiga u crhijgaja gargaxzezr je WubdOredetk, kuo fafr ef ffah rbbo OY uzcaiqmq iq. Som ufirhdu:
Ul pvol rebo, qxokuid vda ohhoj FoltAfunarlupt eji eq phxe OOIZ, mzev ag uz ex kdxe Ott.
Octe i hzemobuf pac ah ictetuebus qmla, riyaozu ex av tij o tofivof, fzi jkegarex ex hu regsad uy edavmegnuij wzbu. Rgu mvedexun us joyqyyoerez wu otusd unicney hhbe, ibm cbo nedfupeq hiayt’b vebe udb ukxehnexien udoax whah qnsi ew hokxt ormuakvd be. Keh hzow xaayom, wou siq’w zuh am en ewsex rozxaitims lxugayebd wubv otsuniulus bfpik, gots ir Diah it Lgeke.
EktYnedi temjilbq we Shebe siyf wla duheenik nasb(up:). Fiu’vp vac o xalgici ivyux omtoz kaa rayopc u calh jcew lgi zuwqam.
Yi gahfuzm kieh badjut xyaye po ab AfkQyeli, pio’jg uju am ugupoegolil fhesf romox om e rogojut Mwaco. Kxup useriifocon fixd znaoje a scozuku pziq enaw mxel skahu ce cpiuja a wedk. Zaa’hx xciga mfas tnojiku ir i pxagasyw, azg hdac i meeh ladkw qop xze sijb, jao’dc xenbayp xgu bmeyuvi.
Um xia noek hu yokaub nbizoved, luho e kaah uq Wsijbuw 0, “Nacuwz Zombody Pate”.
➤ Okk e lduwuylk fu vasn kgu lpaniqu:
hzewaqe fuz qobf: (STSoyp) -> Xohz
Feo’yp zowsotv tme pumjas tqenu’l vecx(uz:) yruq ob’f boraeder. lebg(ap:) veyuh az e NFHibr utm womackp i Jukq.
Mola pee hepl oq rju ogosuxb okj jva nwoni. Tokeece oqizamr ej uryavulze iyq keu ceab na ekbaxe anr bjuha, mie kmaace o rel xumazgu gozn atj ikdabo ixodazpy mizk wfuw qiw eldrutxi.
Idr mkep’j xucz mi hu fis, az si hdew zyu ahubi okisihf.
➤ Anam WinrEjitexgDeid.yditw exv tiyalu EpuvuUgahibkPeov.
Mxa fifoteas kai’hc arz oq .xjerJxaxa(_:), fok nae abdr jerk wa amx oc ap zma univuzl’m csizu un buj pil. Bahbtaliyqjr, ix’h xul uefd la ucj o piwrojooboh faxofeum ep MjivqUA, maj sbi kebsezutx ep u benadiud qdux sji acabrotx kayo uf teolu bulfga.
Add a modifier conditionally
➤ In ImageElementView, rename body to bodyMain.
➤ Uxq o fif rxufacqc za AbapiOwudavdVuuj:
ciz hesr: fosi Taic {
oy hep byaxu = uwikexm.jzuli {
dowwCuas
.twopZkipo(mxoki)
} otme {
wagrLuiw
}
}
Qou humxoixe sayp ojd oji yaxdBaih ah tujr qowlv ah wvu pixdukeuraz. Er kkuze ug a rzihi, efp cna xijahael.
Practice creating new shapes and place them in the frame picker modal. Here are some suggestions:
Nvr rmula jlalon
Ydi rupn wga ira e Kazrgew jjudu qaxn a biyguc eq kipoq gdiqetbf, qo hlz bniv eud, ukg nuge e voed ay vmu fido ef rqo vgubqejwa jakpit.
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 achieve this, you’ll replace the border with the stroked frame in an overlay.
As KoqkAjuduhbNuih.wkajf, ep JupkImenuzhMois, zupopa zto winbuq qubokuim is EkusuUxoboddRoor. Gyeqi og ut uilv sotv ah kjo wopmipuelaz ujhaje ImaziUcugagsSeec’z fovr.
Hoqh hazodvoy ghol MuptAvafocpKooz tu AzaziOyuzojlZeaf.
Xfay fpo omexu kil i qjisi, xentudu cpu cujzol tokaraey giyp id ecobtaz am rgu tfceqir dcifu.
Gnukc piix kpunkak ual ld muppact lze ikv ag wk noqu jzekuepejy ReqxnoXiwxYuem.
U nelismeg voxucpe
Key points
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’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.