How to convert a swift String to CFString

后端 未结 5 954
梦谈多话
梦谈多话 2020-12-30 19:34

How can i create a CFString from a native swift String or NSString in swift

    let path:String = NSBundle.mainBundle().pathForResource(name.stringByDeleting         


        
5条回答
  •  一整个雨季
    2020-12-30 19:57

    If you're trying to convert a variable that contains a Swift string to a CFString I think @freytag nailed it with his explanation.

    In case anyone wanted to see an example I thought I'd include a code snippet where I cast a Swift string ("ArialMT" in this case) to an NSString in order to use it with the CTFontCreateWithName function from Core Text (which requires a CFString). (Note: the cast from NSString to CFString is implicit).

        // 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)
    

提交回复
热议问题