如果您尝试将包含 Swift 字符串的变量转换为 CFString,我认为@freytag 用他的解释将它钉牢了。
如果有人想看一个例子,我想我会包含一个代码片段,我将一个 Swift 字符串(在本例中为“ArialMT”)转换为一个 NSString,以便将它与 Core Text 中的 CTFontCreateWithName 函数一起使用(这需要CF 字符串)。(注意:从 NSString 到 CFString 的转换是隐式的)。
// Create Core Text font with desired size
let coreTextFont:CTFontRef = CTFontCreateWithName("ArialMT" as NSString, 25.0, nil)
// Center text horizontally
var paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
// Center text vertically
let fontBoundingBox: CGRect = CTFontGetBoundingBox(coreTextFont)
let frameMidpoint = CGRectGetHeight(self.frame) / 2
let textBoundingBoxMidpoint = CGRectGetHeight(fontBoundingBox) / 2
let verticalOffsetToCenterTextVertically = frameMidpoint - textBoundingBoxMidpoint
// Create text with the following attributes
let attributes = [
NSFontAttributeName : coreTextFont,
NSParagraphStyleAttributeName: paragraphStyle,
kCTForegroundColorAttributeName:UIColor.whiteColor().CGColor
]
var attributedString = NSMutableAttributedString(string:"TextIWantToDisplay", attributes:attributes)
// Draw text (CTFramesetterCreateFrame requires a path).
let textPath: CGMutablePathRef = CGPathCreateMutable()
CGPathAddRect(textPath, nil, CGRectMake(0, verticalOffsetToCenterTextVertically, CGRectGetWidth(self.frame), CGRectGetHeight(fontBoundingBox)))
let framesetter: CTFramesetterRef = CTFramesetterCreateWithAttributedString(attributedString)
let frame: CTFrameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributedString.length), textPath, nil)
CTFrameDraw(frame, context)