CG Gradient runs on simulator, but not on iPhone

▼魔方 西西 提交于 2019-11-28 22:00:45
Brad Larson

One way to work around this would be to pass UIColors into your function, instead of CGColorRefs, and use an (id)[color1 CGColor] cast for each element of your colors array. This appears to be the most popular way that people are addressing this problem right now.

I point out one use of this in this answer, and there's extended discussion about this in this Apple developer forum thread. If you use a UIColor's -CGColor method at the point of declaring your NSArray, and cast to id, everything's bridged automatically for you. As gparker states in the above-linked forum thread:

The automatic case described by the documentation applies only to calling an Objective-C method that returns a CF type and then immediately casting the result to an Objective-C object type. If you do anything else with the method result, such as assign it to a variable of a CF type, then it is no longer automatic.

As hatfinch points out, this could mean that your CGColorRefs placed in temporary variables won't hang around after the last time you reference your UIColors, unless you explicitly retain them. Like the others in that forum thread, I mistakenly thought this was a bug in the bridging implementation, but I can see that I was reading this wrong.

You're not keeping your whiteColor and lightGrayColor alive. You obtain CGColorRefs you don't own from UIColors that are never retained. Your code should read:

CGColorRef whiteColor = CFRetain([UIColor whiteColor].CGColor);
CGColorRef lightGrayColor = CFRetain([UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0].CGColor);
CGColorRef separatorColor = CFRetain([UIColor colorWithRed:208.0/255.0 green:208.0/255.0 blue:208.0/255.0 alpha:1.0].CGColor);

// ...

drawLinearGradient(context, paperRect, lightGrayColor, whiteColor);
draw1PxStroke(context, sepStartPoint, sepEndPoint, separatorColor);

CFRelease(whiteColor);
CFRelease(lightGrayColor);
CFRelease(separatorColor);

You could petition Apple to declare -[UIColor CGColor] as objc_returns_inner_pointer, which would make your code simpler, but that attribute is really reserved for non-retainable pointers.

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