2012-11-11 67 views
2

我有一個矩形繪製一個NSAttributedString的方法:繪圖NSAttributedString與核心文本爲中心的

-(void)drawInRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self); 

    // left column form 
    CGMutablePathRef leftColumnPath = CGPathCreateMutable(); 
    CGPathAddRect(leftColumnPath, NULL, CGRectMake(rect.origin.x, -rect.origin.y, rect.size.width, rect.size.height)); 

    // left column frame 
    CGFloat translateAmount = rect.size.height; 
    CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
    CGContextTranslateCTM(context, 0, translateAmount); 
    CGContextScaleCTM(context, 1.0, -1.0); 
    CTFrameRef leftFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), leftColumnPath, NULL); 

    CTFrameDraw(leftFrame, context); 

    CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
    CGContextTranslateCTM(context, 0, translateAmount); 
    CGContextScaleCTM(context, 1.0, -1.0); 

    CFRelease(leftFrame); 
    CFRelease(framesetter); 
    CGPathRelease(leftColumnPath); 
} 

我從教程一些幫助把這個在一起幾個月前。事實證明,這是默認情況下,繪製左對齊的字符串。我對Core Text不太狡猾,有誰知道我怎麼能夠用文本對齊中心來繪製它?

(請不要推薦外部標籤繪圖類,我需要使用Core Text來做到這一點)。

回答

0

爲SWIFT 3.0:

final private func drawIn(rect: CGRect, attribString: NSAttributedString){ 

     guard let context = UIGraphicsGetCurrentContext() else{ 
      return 
     } 

     let framesetter = CTFramesetterCreateWithAttributedString(attribString) 

     // left column form 
     let leftColumnPath = CGMutablePath() 
     leftColumnPath.addRect(CGRect(x:rect.origin.x, 
             y: -rect.origin.y, 
             width: rect.size.width, 
             height: rect.size.height) 
     ) 

     // left column frame 
     let translateAmount = rect.size.height 

     context.saveGState() 
     context.textMatrix = CGAffineTransform.identity 

     context.translateBy(x: 0, y: translateAmount) 
     context.scaleBy(x: 1.0, y: -1.0) 
     let leftFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), leftColumnPath, nil) 

     CTFrameDraw(leftFrame, context) 

     context.textMatrix = CGAffineTransform.identity 
     context.translateBy(x: 0, y: translateAmount) 
     context.scaleBy(x: 1.0, y: -1.0) 
    } 


    final private func drawStopMessage(){ 

     let paragraphStyle = NSMutableParagraphStyle() 
     paragraphStyle.alignment = .center 


     let attributes = [NSParagraphStyleAttributeName : paragraphStyle, 
          NSFontAttributeName : UIFont.systemFont(ofSize: 24.0), 
          NSForegroundColorAttributeName : UIColor.blue, 
          ] 

     let attrString = NSAttributedString(string: "Stop\nall Dance", 
             attributes: attributes) 


     let rect = CGRect(x: 20, y: 100, width: 300, height: 300) 
     drawIn(rect: rect, attribString: attrString) 
    }