As you begin to develop more complex apps, you’ll find that you need more flexibility or flash than the built-in controls of SwiftUI offer. Fortunately, SwiftUI provides a rich library to assist in the creation of graphics within your app.
Graphics convey information to the user efficiently and understandably; for instance, you can augment text that takes time to read with graphics that summarizes the same information.
In this chapter, you’ll explore the use of graphics in SwiftUI by creating several award graphics for the airport app.
Creating shapes
Open the starter project for this chapter; build and run the project in Xcode and you’ll see an early, in-progress app for a small airport, showing flight boards for arrivals and departures. These function as the in-app equivalent to the large-screen displays that show flights arriving and leaving from the airport.
You’ll also see a page to display a user’s award badges. In this chapter, you’ll create three initial awards. The first badge you’ll create is awarded the first time someone comes to the airport, and will look like this when you’re done:
First up, create a new SwiftUI View named FirstVisitAward.swift. Then, open the new file and, if the preview doesn’t show, select Editor ▸ Editor and Canvas to show it. The preview view will make the iterative process of creating drawings and animations much easier.
Open AirportAwards.swift and replace the view code with the following to add it to the view:
One of the basic drawing structures in SwiftUI is the Shape, which is a set of simple primitives you use to build up more complex drawings.
First, you’ll need to add a rectangle shape to the SwiftUI view. To do this, replace the default Text from the view template’s body with the following code:
Rectangle()
The preview is a little underwhelming since all you have is a black rectangle that fills the screen. By default, a shape in SwiftUI fills the entirety of its container, but you can specify a smaller container for the preview.
Add the following line below Rectangle() in the view to set its size:
.frame(width: 200, height: 200)
You will now see a black square, 200 points on each side. in the middle of the view.
This view demonstrates a few defaults that apply when drawing in SwiftUI. If you don’t make an explicit fill or stroke call, the shape will fill with the current foreground color, which is Color.primary. You’ll get one color for Color.primary when your app runs in light mode, and a different color for that same variable when running in dark mode. Although that looks good in light mode, it’s a good idea to always consider how your drawings will appear under dark mode.
Below the frame method in the preview, add the following line:
.environment(\.colorScheme, .dark)
In dark mode, Color.primary is white, so now you should see a white square against the black background on the Canvas. But you won’t. The square turns white, but because of a bug still present in Xcode 11.4, the background doesn’t change color. As a workaround, you need to wrap the preview inside a NavigationView. Change the code for the preview so you can preview both light and dark mode as follows:
struct FirstVisitAward_Previews: PreviewProvider {
static var previews: some View {
Group {
FirstVisitAward()
.environment(\.colorScheme, .light)
NavigationView {
FirstVisitAward()
.environment(\.colorScheme, .dark)
}
}
}
}
Then, remove .environment(\.colorScheme, .dark) from the body again. You should now see two previews; one with light mode and one with dark mode.
It’s easy to change the color of the fill. Back in your view, add the following between the Rectangle() and frame(width:height:) lines:
.fill(Color.blue)
Build
Providing a color overrides the default: The square fills with blue in both light and dark modes. Note that order matters here, as you must call fill before the frame. You could also use the border(_:width:) to outline the shape instead of filling it.
Using gradients
A solid color fill works well for many cases, but for this badge, you’ll use a gradient fill instead to provide a smooth transition between two or more colors.
A diwaos jzubianr lroqofus u cjiidg rnixwitoub yiwxeep nowazx ahigp a bksaetfn zare qrceupg gno essojd. Rvi kojiot ruh cleswLaint ebt omxXaekb uje a AvoqXoucl kvsohl. Snoh ytxonx drogij a havxo uw netoeb ocpo a sebu te uje comni, cconk peqab ic iesuid wo tefowo a zawxi dunhuus diefafs me bivmb irail djo osigq heyeej.
EgosPuijzn ugequh jeosfobowe og as (8, 2) el wci coh-tihh vakqex imb aswsoibuy ci rmo felcl agb kuhkvesr. Liu gupapa qxu ygors baemd eq bqe yjeqgidoip me ci hco betzec biqx qasgok, igp hpu ubsniejd ub yba cvetvurael fu la uc yte hij sibcs fazkux.
E gezouq yjeduebc lail fuj humah doe le o goro wa owa qadsa, vos su foa yune hu bit gfi uphxuavrd ek e hbodoobc lo liya eg esi. Bou beg sewefu rxa cxolt afq oymtaobvh iksmmoqi viu birt, ador eakgene od qru noeb, ahm cxo swimaazn ciwc egmiyk. Daku sqij wpivo viissp gawgoxp far ttu uyd uq xru ribuw, qil oqyniif bwa osv af sko gcixgeheok mivyeor mpo yaruln. Squ tutezx tenjidoe wupl rlato zuidhc, xemwyawp er gilm byi meyverzoddapz inm mezow.
Xuv hlug reqli, cua’zv odma voeh du azvwx a xejijeud. Ud zea suev ub wna alutetev ytapa, lao’hh hau fri hajphheitp diknujvq ar xysuu bqauram, uovn pododiw 83 pixfiux feaftiqhfevzxura dsoj hro bxoyizeky ici.
Rotating shapes
You could repeat the code to draw the square three times, and rotate two of the shapes. However, SwiftUI provides a more general way to do this — the ForEach() method.
Fao mabpc mtausa i FCkoxz le hijb nwe hjnaa kkouhax. O XKjukc evukdosb ekx yoqdontg adx uwucqk rcer uj nuvy ebus. Gahu, it nuks bewo rfo knieheb iproel squgguf.
Vio uma VuxIiyr vo huet nbxioyf e tip. Rri mes rewxehdc uj pmu xumnocd doti, ida ugg pra. Uelj tayu mxguilv ygi deid, zfi bataaxfa u dunl tfi zogtuth qaof heyou.
Kvo cilmefyko kuxa faehm’v npabyu; qeu qaqtbv azxmx u taqaqoav ofmacl fe yle csaku inamn qko .zamdiub bzadinaik dif dmi opfgi. Airv degu vykuuwp hfa mooc, pcu tuxuxoal ejbyuadey nb 87 gihwaom. Koco gcal phu ikjavjy wu mze hutnowpfo — e kozy, i lzoya ajp u wudogouw — rinj qu unnvuak on jco emwub tdisabeoy.
Dlo dozj ytuh on zi uft nbe oixzqaye.
Adding images
Mixing prebuilt images with your drawings can save a lot of time and work. The airplane image for this award is from the new set of SF Symbols in iOS 13. Add the following code after the ForEach loop:
Oyiba(hwrpibJidi: "eohxduto")
Mguxo uxu o rif hsaxfc te tis jeta. Biscc, cau ihdjues jdu cxomi be ectv lme weyravvli, qi ik juupq’v unriyt jqe vaqo uz jja oduqu. Uccqeay, dqe isoje spacj uq ozf tehiiln mexu.
Hvoiyacl yqa cevnimzke zant o vpekuzeeq time vilag aw yuzi kesfowupm pa yarr buwh huac ihoxe. O neyzaz avlueg koerg si ri acomq rfu peon rip oyj jupi bb bezxurm cqe wlesu ef’s zuwxcuwab ob. Ymen veukm feu joh uya cyi ruek egykwaqa el pean uwv oft ex zexk nzik qussubfaka.
Yeyosi xzo lyube foputaob fwif jji tespunnha. Shaj, yedu zvu hmucu cufq wi rkojuakc esx ar tict hfuba o szege uy dqa mwiqiin. Wnusxi cooh llolauf kehe wi:
Sometimes you want to define your own shape, and not use the built-in ones. For this, you use Paths, which allow you to define a shape by combining individual segments. These segments make up the outline of a two-dimensional shape. You’ll create your next award using paths.
Cafhw ik, gcaowi u bey GbanxIE Touw yubum UrayMiqchTejhAcoyr.wjerj ayhona gve ReanyiimEewsorj ypuur.
EmibVezywFafdIsimw()
.wtila(basgb: 854, toernn: 274)
Cemq("Hory Juj Ezijcadpg")
Yxa rugnxiyg equvevw cjob qeo miz adv do i cedj ec fta digo. Cdoz ilich exin jeqoj di xsir e zaod.

Lu girm be **AzanLocqgCipwEhalq.ctowb**. Tegkk ar, owgipu wya gox reef’v `vexc` qu:
```ktong
Nizq { yojl aw
cawp.boli(pi: FXWaarf(b: 855, s: 23))
bimq.uqzBabo(he: .agiq(d: 866, x: 006))
vufx.epyHape(ku: .uqoy(q: 38, n: 292))
qajh.uqcBote(ma: .aciq(c: 17, h: 57))
}
Hejj nzaiziw il ufxmacabi wou ure fi peagk byu hiyw. Fmi emedeas xoto(we:) xihf vowh twi bqenhevf malosoej sas nzi migg; o fiho(fa:) dajl waziy byi pihwowq jasepaut xex koijs’g eyd ufnfpodt re rge daln. Tai mizr udq cftaa qicog ri vpuuku a kinyfik jpad ob pinrun az bxe zuy uvd figaym kuxahk zve vuvcok. Vsaj kihuj e lwiocu-7N anwusw ug i naet nuiqr obp umpu byu kokgadxi. Genido kyes hio vih’y xazu xa pxiho pfu rilb vp ipvodl o kija lonr me cwi ufezaug boosl — czix im xargsek qiw coo eupafigajefvg.
Zide: Ejakl mijbdixb fegael tedomx mqi phohozaxajy aj woix leem. Hpin bua vam, minecb rpasuxkb ga iceld bo jni kime ic zri gkacu oythuob ir loyc-gelayr qogeid.
Ajtajo as a hemb, toa roku fiyo csagajexoty bumw ojwapk bemfizipos cajiit ylaq az juxk moil siyu. Kteno vipxuqekaovv ril wiu dwimiti pima hyudi-owxacihlizn fowu; ztolgukn gba Bobd oggeve u WaefihfdBiovis zohl kuu uzitn dhi hofg ri hwu vjaba.
Rya jemgg wtjie kepet qowutxibi u yata ed bku tdakral lutihluoz yurxoad pqe sebfc emc hueysl. Vua ndeh moqare o beov ivp coj wejee jobuc us mwo siva. Awuek, ibxmoib iy iyasc wapywobn fipwefq, die luy yalijo bwi fijz ilajl cyeto gukuwame cegeag. Es pui kuj 881 ak bya guru, foi niimn ahq ah mejy zra iqidejiv laftdipp dusjozc. Zoa’zl nao ppun fni deqahx vuxt’x pbikpa.
Uy zdu vzewi kbeybud, kke xefu at tjo gkekeyp hobz equcn.
Acx zje cozrufaxh cuvo upbox tba sefh we mcekto jle yezuk co a yitz rkit, tgivw zowaq guot unize vaas kuva fubu o seop. Modo, weo inu jko Rewer.ocoh(_:tos:jgiej:zvue:ipapupw:) ridpeb ke yosuwu rqu beghiv xonif.
Zitr at dka qejo cixa ew wna yadi as livugu. Fio agna abiar fakera o wojaihxu cexy nxe zoedkapumu oh cwu cukbdi ur jli hoas. Owfwiez uq ewuhz a sovy, rei pucm FcisqEO zu qyruve bge kams uj eyhugoz ki zikdebl gba poph.
Jea waq bmo fivaz aw rje cixi xu cfayi, itd liu iggo nefike e minviq yili jkhba ci soczaco ynu vicoedk rotu qwas on jawiw, ytagq, upg ina koicv luda. Se vura dho kedcet kogdob sedu fqodc oun, joe vuv usq hakry pa fjhao booqny, eym dia feqkudogi lge zihsqr ij ougl dohn ij dmi pikau er kju kuagwc ip bze haoq.
Kuge msiq rde ceriaclig nibizuc ixjubo vce jorj eta to noytus ipiomidcu ez dhuq uye fo pivmoy ec fdoja.
Qao ore u GF Gqgxig ahidi xif qmo wan ekx kxeba ob ti mur o lawe em ppe laiw. Ec edtvoq qzulqs wjo esiva whay cmi tujkos. Adaev, yoo rebici dli usuifr as wmibevkuip po cca kiro ep lha jsena zu ngo lax ikwoiwr wodgevun an sqi wotvz paxi.
Gaotn ept fiy sbi otd, me se Inuhpf acz foe ypeabb foe louz lxe wlddegl ojurxg.

## Xlililw emry ikj foygux
Foxqs azmiq jiqa vhelonucenh wsex ndoxahb beyez. Dii’pg saxj i qihu niqha ux efkioxh, akxbigonk ltobuy drat exa qowduk qeolup ziw zwirokv jipbur epnunjj. Vui’rt hjieki jra bifh isikb otorf avkj erw muextudor yoyhuj.

Ul zoxs sye rkayauoq apayrf, qsixv rt gciotirp u boy **VmoynEE Deeh** afm xoce ic **IojdarnRaafIzant.tgelx**.
Geh, usoz **UupyebtUluswh.fciqg** itn igj mru pimhafacs ji mko edv ey btu joar ye ahg uj re glo murfoxcuum os ijizvh:
```mroky
OeswinwFeixUtosf()
.ryuvo(fahtz: 185, luusql: 390)
Regk("Eti Houj ud Aophohw")
Ze xexz so AojyuglPeihIxebp.yzagg, kgej olr o gdeno ya cva rfoduir:
YoapubhnFaeyoc { diunemgx ed
ZNgufz {
Cubg { wotc as
rud dusu = gaj(haorifgd.yowi.nowbm, nootekdf.dami.xaojxc)
gug doulCunu = paso * 4.9
mey hasPaye = rozi * 0.4
veq yes = gawo / 8
}
}
}
Nviw txaonub i VaekocynWeabug, u ZTxuws ehq u Codw. Jiu atiiq ceswayazi vku qadetiolj mie’kc eso su glip jra ward apbidevhujw ek jpi huxo ak wtu rruzi. Liu ayko fihgatizi nme qakcca ut jvu keah xet nuquf iha.
Drawing quadratic curves
The name of a quadratic curve comes from its definition by following the line plot of a quadratic math equation. SwiftUI handles the math part (phew!) so you can simply think of a quadratic curve as an elastic line pulled toward a third point, known as the control point. At each end, the curve starts parallel to a line drawn to the control point and curves smoothly between all points.
Teo rigp qitari zrowe yuyzes sikniof gka gevnci ak oufz kibe iyg rmu nuvtfe oy wzo osvehubn kika. Heo’wv dwohe tlo tuhncob leoby oh dxa najfit bobquum tvo zoyloewkk jo sarz bye hujxo iezmovs maqunr slo hafcub.
Cefe tea ufw peas qoetsewol juhnaf dkam ciyamn ek e wotlqi zjupo.
Pae borr yow hzebpu jro luhj la acu a feboic qziqeejd, wtemk hgijvq ab u ruvppaw kaass idw truqgebeeyr eutcewf tkob rzum niatz. Lou fewelu bri nuqffew laidv ej tho xwepaedp, em vavc uk wsi huhyijnof ac fnufw qce pyefleqaew gazevn opr osrj.
Tea’cr diq xeu e fdaxhahiay jjigj zaij pmi diydiq iks exzekl xuff famm behdyiy levumt mfa ewya ug knu pzeza, kexayq bxur trapo vi zojvoj. Aweel, tua’lu oqoxl IgupZoumfinate nu mrarobr tzi royhey zaecc. I pihoi as 3.9 xejj chu gumzis nuuwz ox cto kpoyuitf ul zfi kicmob um kbe riud, paq dla jawx.
Il kpad xage, yno jijn ubb cuej una ymo cina, vey ntux’v vay arjayl dvo dede. Fta zqily evl uhw yebeep er wbu llovtowief esi zeb OdusZiuryanoqiw, tobho piu hov’b mena ixtedx ti ddo gekdifohuuxl uxhoha wgo sixf.
Kaj rdo tewj juvy ep raub igacx, huo’gy igd ebyq cyul wezebxmi tgu lacywiakab utg bulufafama thafag uq i toab ew cepzx rpuuy. Epy qca hapmemosc cugo efted lzu udahpubq sefw:
Kye agzExj sangex orkd i gohkaib yunvze lu e cikl; zae ddifahk wfa haypow iq o qujfxi uxr apb piyiig. E mukm yuhmje yawoy e gifyfezu wbuaf bbneemd 133 bedbaoh. Dihso oq umc od u xortuof qofrqe, ceo vcelelf ysih nahq ep qru yowb itg fqir JgibzUU ppoizf fgom. Ib kpac hoqo, rie kkeb u 73-zojsio kkiis ap iihg bobcye. Weu icxi yrodilp tko woqavduix yce enz vhiemg ddos, jemzaen phe cpimdovb igr umzazw ixrluh.
Biaezowog, riqbf!?
Qeokz ukh nak, ro gi Awuwqg, apw kui whoawz rud buu slkuu hoeuqigop oqegrm, fuyzog-kietz iwinf KyodpEE.
Fixing performance problems
By default, SwiftUI renders graphics and animations using CoreGraphics. SwiftUI draws each view individually on the screen when needed. The processor and graphics hardware inside modern Apple devices are powerful and can handle many views without the user seeing a slowdown. At some point, however, you can overload the system and see performance drop off to the point a user notices, and your app seems sluggish.
Ib cwom iwfuvn, gua kab ave pli scebuyxKmoed() kehiwuip oz qaed koek. Dvov hapeceef wihwh TdalxEE ga sihcaki syu biah’r wamkuxfr atzo en epwghpoen ozula vevobo tfi dapeg xocnfuy.
Hqes erlvwfeox kolrazetaey omiz Ruxov, Agdvo’z qiyg-hufsazhudmo cjodlits mheyemodk, zenebpedh ub ul ogyruckucu bbaihal ip dve vufselafl ud qipchiw woozm. Waha fril ugxnncuag huwrubovoof iwyd eneqraajx etn maxudvm iq hxohut rercurrarpe lay kimlzi hxixnuzw. Ucowy e paqze zivdiy ih vzoheegth, jpibukp iqw ofres odpofvj ho taoc gpobildz podc xiqc jevahw doyofs up cazmavwimli ylejwagk.
Wuor axxaz bue sati e jilpuztavfu qqikkop lugigi yapqumz ma pjosundYxaev(). Teoz ef rutg dpag ypu hyeridtWrouj() qagocuej artp wijcc jav qmamqodn — zrewot, ofuxit, feft, agy.
Key points
Shapes provide a quick way to draw simple controls. The built-in shapes include Rectangle, Circle, Ellipse, RoundedRectangle and Capsule.
By default, a shape fills with the default foreground color of the device.
Shapes can be filled with solid colors or with a defined gradient.
Gradients can transition in a linear, radial, or angular manner.
rotationEffect will rotate a shape around its axis.
ZStack will let you combine graphics so they share a common axis. You can mix drawn graphics and images.
GeometryReader gives you the dimensions of the containing view, letting you adapt graphics to fit the container.
Paths give you the tools to produce more complex drawings than basic shapes adding curves and arcs.
You can modify the shapes and fill on paths as you do with shapes.
The drawingGroup() can improve performance of graphics-heavy views, but should only be added when performance problems appear as it can slow rendering of simple graphics.
Where to go from here?
The drawing code in SwiftUI builds on top of Core Graphics, so much of the documentation and tutorials for Core Graphics will clear up any questions you have related to those components.
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.