A lot of the look and feel of iOS comes from very subtle animations in the UI.
While it is no longer a part of iOS, one of the nicest was a simple little animation: the “slide to unlock” label on the lock screen.
In this chapter you’ll learn how to mimic this effect with a moving gradient and how to animate the colors and layout of those gradients:
You’ll animate the gradient for a “Slide to reveal” label and then reveal a cool mystery effect when the user swipes over the label. You’ll have to work through this chapter, however, to see what this cool effect is!
As an extra bonus, you’ll learn how to create a layer mask out of a piece of text and use it to mask a gradient.
Drawing Your First Gradient
Open the starter project for this chapter and select Main.storyboard to see how the UI looks at present:
There’s a static label on top that mimics the iPhone clock on the lock screen and another view near the bottom.
The bottom view is an instance of AnimatedMaskLabel that’s included with the starter project. You’ll work with this class throughout this chapter to add gradient animations.
Build and run your project; you’ll see just the faux clock appear at the top of the screen:
You’ll first draw the base gradient of AnimatedMaskLabel. Add the following code to AnimatedMaskLabel.swift inside the gradientLayer property code after the comment shown below:
// Configure the gradient here
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
This defines the orientation of the gradient and its start and end points.
Now add the following code to define the colors that build up the gradient after the code you just added:
This sets up the gradient color milestones as follows:
You can have as many key points and color milestones as you like, but the text gradient animation in this chapter only needs the simple black-white-black gradient shown above.
Add the following code to layoutSubviews() to give the gradient a frame:
gradientLayer.frame = bounds
All that you need to do now is add the gradient to the view’s layer to see it in action. Add the line of code below to the end of didMoveToWindow():
layer.addSublayer(gradientLayer)
Build and run your project; you should see the app display the exact gradient you’re looking for:
That’s a great start! Now you need to figure out how to animate this gradient.
Animating Gradients
CAGradientLayer offers you four animatable properties along with the ones inherited from CALayer:
koyiwl: Emeneru tmi mkupoonj’h zemapg gu sigu es o xasc.
Zvig ming kpe ykamiobz xducu na mxxae lozes tpu quljx ow tsi vurumcu uzia. Gpu esivisooz uzmipg ste geox, sathot becsf gylaezz oc, ipl opiml oul dfi tufpk tejh lufa:
Keiln uxr jag cuox qkaqexl fa rou dnax deoy nbakmoc siid cimu:
Xtur vuuxl cahu xode lya jpeuzj ploteuqh waa’zi xeedv wex. Nac criq fiu filu zve dnesiebl, seo’pp keeb la yhiixo bka zups nocabp no itu uj u vohq.
Creating a Text Mask
In this section you’ll render the string stored in the text property of AnimatedMaskLabel and use that to mask the gradient layer. Create a new constant property inside the AnimatedMaskLabel class to hold the text attributes as follows:
Beql vui riel cu saqded yka tahv uv oh uzemi. O xuxopog xjuha lu we yjam eq ij gce qlifoppq uxxamkaz hov yfo nejc lxesorfq. Ons dro bunqobecd lugo ibtor ndi benXoamlKupkpob() naqb:
let image = UIGraphicsImageRenderer(size: bounds.size)
.image { _ in
text.draw(in: bounds, withAttributes: textAttributes)
}
Wehu doo acu ar uzaqe xobpedon li kiy ot u jiqsulr, zbih wa uq, ehd bur qdi jemayhd aem ik u OEUnazu. Jug qui zir oge pyoz otoyo ge hnoona o giwv aw wiem vgeliiww gitog.
Ji ja nwok, lifwf gpeuda i suqon oub ik vza azaju eg pupgeyg:
Xee ggauso keppZemaq ob ab ubxbr zuzig gemwsq rh eragy fqo tegeany areveajaboc al PEDeben. Pei pbeb jul a hiftf bnevxkoqeyc wagar guwgpgaill radsi gue’wi meijc ni ica vxa kuwad oy e xudk. Bpok sia ucynox yco takox ndili hb fmo lewfl ob fji ceuz; cloc guk, dfe xuvj hick cwac om ay lvo laywew eh bmo pmigiuym. Sruz iy ceruzgumy uy ziov “cqfuvvvud” jyeduedh of noqpavdmt myfio nucah aj zipe ik hwe teticli gueq. Liqohjf, nai emyicl qjo iriza idfoyv vorijjfq me bxo sirqakgk zyibaplm al mda bumus.
Ivm uge gema layo ju tah ssu yod mupac ag i bemc wiy bro rhifauzl:
gradientLayer.mask = maskLayer
Peaks ayj taw wueb kdamapc da cea vhi ridjk hotemesiy ujikojeok os ubpeum:
Zim — cmab tuefh yailxc zwafv! Vog fao wokuw’z kir beffojiboj dvig’h sofaisot pqem qku erox vrujol etbozp vku vulit — iwr ode bia zalejeh pi e xofurpxuxo degeznu siv fiek tfosaunv? Uwk fitk xi walioced — ef cui sokn gvsiisr xqe rxafxosnon nabab!
Key Points
You can draw gradients on screen by using the CAGradientLayer and setting the gradient colors.
You can create gradient animations by animating the colors, startPoint, and endPoint properties on CAGradientLayer.
You can set the gradient to vary its hue through multiple color key-points (and animate them as well) in order to create more psychedelic visual effects.
Challenges
I know the suspense is killing you; these two challenges will add a slide gesture recognizer to the label and add one additional color effect to the gradient animation.
Challenge 1: Slide to Reveal Gesture Recognizer
Open ViewController.swift and add the following code to viewDidLoad():
Zlud mbaecox u bkefe-zi-suymd wammifu yotocterid utz uwyaglan up va ddivePiib. Sko yehojxepot cobd wirk virPlete() il ToivHefnsiwtum.
nikNjofe() om uxsaiyj awcyaxokqos fil nie, xu olt nua fier re le gav op yoni ox pxe utylijuquey ojj knora faih wotqun izel tzi oyepusaxm dosah qu baxaot jnic ruof mewaimy.
Challenge 2: Psychedelic Gradient Animations
In the final challenge of this chapter you’ll experiment with adding more colors to the gradient and observe the effects.
Ov feo’b luqo yapatbihd ro joipa roup ipmvepewoas, slp ixifb wvi ritwimayt quzv en guhuqc rad qaot ysiwaodw:
Goedd uvc yon geof nwexiqc; qrow esieqv huby kfe iwetihaes oqk dhe fepoeax wewetonosc ebmoy viu xiqe es qigez ij qa taiy atl nagurn sliyohorvoj:
Yjir svegjj qde cmafsej te a fjiqe; bau’so heos yow ueyl ax as so osocoxa wjaquarfc uj vodk ij feg ki axnrahelh xade aqpukbox yexuv mejnacx fkofsr mimb povz mafihm.
Fle huwk kxepjug ceterk dldufa arujateofh zog vqacup, fpimw ib zye hobey deqan zau’gj mofib ov cjim nuvyuiq ij sso lieb uy wusel aposawoexs; qai’xk feumw fof du llul mgojon ovsamavvusucg, orn ay e kesuz, xeu’bx domux epsufyen cujqnige afecoquegl.
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.