Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does -[UIColor setFill] work without referring to a drawing context?

It escapes me why this code, inside drawRect:, works:

UIBezierPath *buildingFloor = [[UIBezierPath alloc] init];
// draw the shape with addLineToPoint
[[UIColor colorWithRed:1 green:0 blue:0 alpha:1.0] setFill]; // I'm sending setFill to UIColor object?
[buildingFloor fill]; // Fills it with the current fill color

My point is, the UIColor object gets a message setFill and then somehow the stack understands that this UIColor will now be the fill color, isn't this just weird and wrong? At the very least I would expect setting fill by calling some CGContext method... But now instead of representing a color, UIColor goes on and does something to change the context of my drawing.

Could someone explain what is happening behind the scenes, because I'm totally lost here?

I did check out these references before posting:

http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIColor_Class/Reference/Reference.html http://developer.apple.com/library/ios/#documentation/uikit/reference/UIBezierPath_class/Reference/Reference.html

like image 793
Morgan Wilde Avatar asked May 09 '13 16:05

Morgan Wilde


2 Answers

The implementation of UIColor setFill is written to get the current graphics context and then to set the color on that current context. Essentially it does this for you:

UIColor *color = ... // some color
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(ctx, color.CGColor);
like image 51
rmaddy Avatar answered Oct 16 '22 17:10

rmaddy


My point is, UIColor object gets a message setFill and then somehow the stack understands that this UIColor will now be the fill color, isn't this just weird and wrong? At the very least I would expect setting fill by calling some CGContext method... But now instead of representing a color, UIColor goes on and does something to change the context of my drawing.

It is because all this is taking place within the current CGContext. That is why your code works only if there is a current CGContext (as there is, for example, in drawRect: or in a UIGraphicsBeginImageContextWithOptions block).

It will probably help you a lot, at this stage of your iOS study, to read the Drawing chapter of my book: http://www.apeth.com/iOSBook/ch15.html#_graphics_contexts

like image 26
matt Avatar answered Oct 16 '22 17:10

matt