For the More Curious: Programmatically Generating Content

In this chapter, you set a layer’s contents with an image file. Now let’s look at setting a layer’s contents programmatically. There are two ways of drawing to a layer that use Core Graphics: subclassing and delegation.

In practice, subclassing is the last thing you want to do. The only reason to subclass CALayer to provide custom content is if you need to draw differently depending on some state of the layer. If this is the approach you wish to take, you must override the method drawInContext:.

@​i​m​p​l​e​m​e​n​t​a​t​i​o​n​ ​L​a​y​e​r​S​u​b​c​l​a​s​s​

-​ ​(​v​o​i​d​)​d​r​a​w​I​n​C​o​n​t​e​x​t​:​(​C​G​C​o​n​t​e​x​t​R​e​f​)​c​t​x​
{​
 ​ ​ ​ ​U​I​I​m​a​g​e​ ​*​l​a​y​e​r​I​m​a​g​e​ ​=​ ​n​i​l​;​
 ​ ​ ​ ​i​f​ ​(​h​y​p​n​o​t​i​z​i​n​g​)​
 ​ ​ ​ ​ ​ ​ ​ ​l​a​y​e​r​I​m​a​g​e​ ​=​ ​[​U​I​I​m​a​g​e​ ​i​m​a​g​e​N​a​m​e​d​:​@​"​H​y​p​n​o​.​p​n​g​"​]​;​
 ​ ​ ​ ​e​l​s​e​
 ​ ​ ​ ​ ​ ​ ​ ​l​a​y​e​r​I​m​a​g​e​ ​=​ ​[​U​I​I​m​a​g​e​ ​i​m​a​g​e​N​a​m​e​d​:​@​"​P​l​a​i​n​.​p​n​g​"​]​;​

 ​ ​ ​ ​C​G​R​e​c​t​ ​b​o​u​n​d​i​n​g​B​o​x​ ​=​ ​C​G​C​o​n​t​e​x​t​G​e​t​C​l​i​p​B​o​u​n​d​i​n​g​B​o​x​(​c​t​x​)​;​
 ​ ​ ​ ​C​G​C​o​n​t​e​x​t​D​r​a​w​I​m​a​g​e​(​c​t​x​,​ ​b​o​u​n​d​i​n​g​B​o​x​,​ ​[​l​a​y​e​r​I​m​a​g​e​ ​C​G​I​m​a​g​e​]​)​;​
}​
@​e​n​d​

Delegation is the more common way to programmatically draw to a layer. This is how implicit layers work, but you can also give an explicit layer a delegate. (However, it is not a good idea to assign a UIView as the delegate of an explicit layer. It is already the delegate of another layer, and bad things will happen.)

A layer sends the message drawLayer:inContext: to its delegate object when it is being displayed. The delegate can then perform Core Graphics calls on this context.

@​i​m​p​l​e​m​e​n​t​a​t​i​o​n​ ​C​o​n​t​r​o​l​l​e​r​

-​ ​(​v​o​i​d​)​d​r​a​w​L​a​y​e​r​:​(​C​A​L​a​y​e​r​ ​*​)​l​a​y​e​r​ ​i​n​C​o​n​t​e​x​t​:​(​C​G​C​o​n​t​e​x​t​R​e​f​)​c​t​x​
{​
 ​ ​ ​ ​i​f​ ​(​l​a​y​e​r​ ​=​=​ ​h​y​p​n​o​L​a​y​e​r​)​
 ​ ​ ​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​U​I​I​m​a​g​e​ ​*​l​a​y​e​r​I​m​a​g​e​ ​=​ ​[​U​I​I​m​a​g​e​ ​i​m​a​g​e​N​a​m​e​d​:​@​"​H​y​p​n​o​.​p​n​g​"​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​C​G​R​e​c​t​ ​b​o​u​n​d​i​n​g​B​o​x​ ​=​ ​C​G​C​o​n​t​e​x​t​G​e​t​C​l​i​p​B​o​u​n​d​i​n​g​B​o​x​(​c​t​x​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​C​G​C​o​n​t​e​x​t​D​r​a​w​I​m​a​g​e​(​c​t​x​,​ ​b​o​u​n​d​i​n​g​B​o​x​,​ ​[​l​a​y​e​r​I​m​a​g​e​ ​C​G​I​m​a​g​e​]​)​;​
 ​ ​ ​ ​}​
}​
@​e​n​d​

For both subclassing and delegation, you must send an explicit setNeedsDisplay to the layer in order for these methods to be invoked. Otherwise, the layer thinks it doesn’t have any content and won’t draw.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.140.204