如果您想将包含Swift字符串的变量转换为CFString,我认为@freytag在他的解释中已经解决了这个问题。
如果有人想看一个例子,我想我可以包括一个代码片段,在这个例子中,我将一个Swift字符串(在这种情况下是"ArialMT")强制转换为NSString,以便与Core Text的CTFontCreateWithName函数一起使用(该函数需要CFString)。 (注意:从NSString到CFString的转换是隐式的)。
let coreTextFont:CTFontRef = CTFontCreateWithName("ArialMT" as NSString, 25.0, nil)
var paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
let fontBoundingBox: CGRect = CTFontGetBoundingBox(coreTextFont)
let frameMidpoint = CGRectGetHeight(self.frame) / 2
let textBoundingBoxMidpoint = CGRectGetHeight(fontBoundingBox) / 2
let verticalOffsetToCenterTextVertically = frameMidpoint - textBoundingBoxMidpoint
let attributes = [
NSFontAttributeName : coreTextFont,
NSParagraphStyleAttributeName: paragraphStyle,
kCTForegroundColorAttributeName:UIColor.whiteColor().CGColor
]
var attributedString = NSMutableAttributedString(string:"TextIWantToDisplay", attributes:attributes)
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)
let url = NSURL.fileURLWithPath(path, isDirectory:false)
呢? - David Berry