Drawing rotated text with NSString drawInRect

前端 未结 5 1850
借酒劲吻你
借酒劲吻你 2020-11-29 04:09

I found this answer on how to draw rotated text with NSString drawInRect:, but I\'m not sure how it works since it only sort of works for me: https://discussions.apple.com/t

5条回答
  •  鱼传尺愫
    2020-11-29 04:37

    KoNew's Solution in Swift:

    extension NSString {
    
        func drawWithBasePoint(basePoint:CGPoint, angle:CGFloat, font:UIFont) {
    
            var attrs: NSDictionary = [
                NSFontAttributeName: font
            ]
    
            var textSize:CGSize = self.sizeWithAttributes(attrs as [NSObject : AnyObject])
    
            // sizeWithAttributes is only effective with single line NSString text 
            // use boundingRectWithSize for multi line text
    
            var context: CGContextRef =   UIGraphicsGetCurrentContext()
    
            var t:CGAffineTransform   =   CGAffineTransformMakeTranslation(basePoint.x, basePoint.y)
            var r:CGAffineTransform   =   CGAffineTransformMakeRotation(angle)
    
    
            CGContextConcatCTM(context, t)
            CGContextConcatCTM(context, r)
    
    
            self.drawAtPoint(CGPointMake(-1 * textSize.width / 2, -1 * textSize.height / 2), withAttributes: attrs as [NSObject : AnyObject])
    
    
            CGContextConcatCTM(context, CGAffineTransformInvert(r))
            CGContextConcatCTM(context, CGAffineTransformInvert(t))
    
    
        }
    
    
    }
    

    To use:

    let fieldFont = UIFont(name: "Helvetica Neue", size: 14)
    
    myNSString.drawWithBasePoint(CGPointMake(bounds.width/2, bounds.height/2), angle: CGFloat(-M_PI_2), font: fieldFont!)
    

提交回复
热议问题