Only White Fill Color is Transparent in UIView

♀尐吖头ヾ 提交于 2019-12-21 04:17:07

问题


I've got a UIView that is set to opaque = NO and it all works nicely. In the drawRect I'm doing custom drawing, and this works

CGContextSetFillColor(context, CGColorGetComponents([UIColor blueColor].CGColor)); 
CGContextFillRect(context, labelOutside);
CGContextAddRect(context, labelOutside);

but this

CGContextSetFillColor(context, CGColorGetComponents([UIColor whiteColor].CGColor)); 
CGContextFillRect(context, labelOutside);
CGContextAddRect(context, labelOutside);

results in NO fill being produced (you can even see other stuff that I drew on the CGContext through it). How can I draw a white fill?

Note: If I set the control not be opaque, it still doesn't work.


回答1:


Why not use CGContextSetFillColorWithColor? Then you can pass the CGColor object directly instead of extracting its components and assuming it's in the same color space as the context.

Edited to add:

this works

CGContextSetFillColor(context, CGColorGetComponents([UIColor blueColor].CGColor)); 

but this

CGContextSetFillColor(context, CGColorGetComponents([UIColor whiteColor].CGColor)); 

results in NO fill being produced (you can even see other stuff that I drew on the CGContext through it).

As I mentioned, this way of setting the fill color assumes that the color is in the same color space as the context.

Normally, most CGContexts are in an RGB color space. whiteColor, on the other hand, is almost certainly in a white color space, which has only one or two (white and alpha) components.

So, since the context is in an RGB color space, CGContextSetFillColor expects to be passed three or four (red, green, blue, and alpha) components. When you get the components of whiteColor's CGColor, you get a pointer to a C array holding only two components. CGContextSetFillColor will read the three or four components it wants no matter what; if you pass fewer, it may find garbage after them, or it may find zeroes.

If it finds a zero in the alpha position, then the result is that you have set the fill color to something between yellow (red=1.0, green=1.0, blue=0.0) and white (all three=1.0) with zero alpha. That's what causes the fill to not show up: You are filling with a transparent color.

The problem is that mismatch between the color space the context is in (with three or four components) and the color space the color is in (with one or two components). The solution is to remove the mismatch, which is what CGContextSetFillColorWithColor does: Since you are passing the whole CGColor object, not just an array of numbers, Core Graphics will be able to set the context's color space to that of the color object and interpret the color object's components correctly.



来源:https://stackoverflow.com/questions/3742971/only-white-fill-color-is-transparent-in-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!