CoreGraphics绘图: CGContextSetFillColor特定颜色无效问题

当使用CoreGraphics的CGContextSetFillColor时,如果颜色空间不匹配,可能导致填充颜色无效。通常,CGContext处于RGB颜色空间,而某些颜色可能只有白色空间的两组件。这会导致CGContext尝试读取三个或四个组件,但颜色对象可能只提供一到两个,从而产生错误的颜色,如透明的黄色或白色。解决办法是确保颜色空间与颜色对象匹配,让Core Graphics正确解释颜色组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        

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.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值