Using NSString's drawAtPoint method in place of CGContextShowGlyphsAtPoint problems

别来无恙 提交于 2019-12-04 03:14:28

Answering my own question:

NSString drawAtPoint:withFont: makes use of the context stack, and from where I was calling this method the stack was empty. Wrapping the call with

UIGraphicsPushContext(context); and UIGraphicsPopContext();

did the trick.

For completeness, here is the code needed for Cocoa. Also works with .drawInRect...

CGContextSaveGState(context)
let old_nsctx = NSGraphicsContext.currentContext() // in case there was one
// force "my" context...
NSGraphicsContext.setCurrentContext(NSGraphicsContext(CGContext: context, flipped: true)) 

// Do any rotations, translations, etc. here
str.drawAtPoint(cgPt, withAttributes: attributes)

NSGraphicsContext.setCurrentContext(old_nsctx)// clean up for others
CGContextRestoreGState(context)

This is mostly not needed, as @davbryn says, as normally there is already a "working" context on the stack that is the same (you hope!) as your context, however, as he points out, sometimes there isn't. I discovered this problem particularly with MapKit MKOverlayRenderer's drawMapRect:, which simply wouldn't show text without setting the context explicitly.

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