为什么 - [UIColor setFill]在不参考绘图上下文的情况下工作?

Mor*_*lde 12 graphics cocoa-touch uicolor ios

它逃避了我为什么这个代码在里面drawRect:工作:

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
Run Code Online (Sandbox Code Playgroud)

我的观点是,UIColor对象得到一条消息setFill然后不知何故堆栈理解这UIColor将是填充颜色,这不是奇怪和错误吗?至少我希望通过调用某种CGContext方法来设置填充...但现在不是代表颜色,而是UIColor继续并做一些事情来改变我的绘图的上下文.

有人可以解释幕后发生的事情,因为我完全迷失在这里吗?

我在发布之前检查了这些参考文献:

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

mat*_*att 14

我的观点是,UIColor对象得到一个消息setFill然后以某种方式堆栈理解这个UIColor现在将是填充颜色,这不是奇怪和错误吗?至少我希望通过调用一些CGContext方法设置填充......但现在不是代表颜色,UIColor继续并做一些事情来改变我的绘图的上下文.

这是因为所有这些都发生在当前的 CGContext中.这就是为什么你的代码只能如果当前CGContext上(如存在,例如,drawRect:或在UIGraphicsBeginImageContextWithOptions块).

在你的iOS学习的这个阶段,它可能会帮助你阅读我书中的绘图章节:http://www.apeth.com/iOSBook/ch15.html#_graphics_contexts

  • 很高兴我能帮助你!一开始我也发现同样的事情令人困惑,这就是为什么我花了这么多精力来清楚地解释它。 (2认同)

rma*_*ddy 6

UIColor setFill编写实现以获取当前图形上下文,然后在当前上下文中设置颜色.基本上它是为你做的:

UIColor *color = ... // some color
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(ctx, color.CGColor);
Run Code Online (Sandbox Code Playgroud)

  • 像`setFill`这样的方法的全部意义在于使用当前上下文时非常方便.还要看一下像`NSString drawAtPoint:`(`NSString`的类别方法)这样的方法.它也是一种方便的方法,可以更容易地使用较低级别的Core Graphics API来使用更高级别的类. (3认同)