vertically align text in a CATextLayer?

后端 未结 15 1372
时光说笑
时光说笑 2020-12-10 10:41

I am working on a CATextLayer that I want to use in both Mac and iOS. Can I control the vertical alignment of the text within the layer?

In this particular case, I

15条回答
  •  天命终不由人
    2020-12-10 11:04

    Updating this thread (for single and multi line CATextLayer), combining some answers above.

    class VerticalAlignedTextLayer : CATextLayer {
    
        func calculateMaxLines() -> Int {
            let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity))
            let font = UIFont(descriptor: self.font!.fontDescriptor, size: self.fontSize)
            let charSize = font.lineHeight
            let text = (self.string ?? "") as! NSString
            let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
            let linesRoundedUp = Int(ceil(textSize.height/charSize))
            return linesRoundedUp
        }
        
        override func draw(in context: CGContext) {
            let height = self.bounds.size.height
            let fontSize = self.fontSize
            let lines = CGFloat(calculateMaxLines())
            let yDiff = (height - lines * fontSize) / 2 - lines * fontSize / 10
    
            context.saveGState()
            context.translateBy(x: 0, y: yDiff) // Use -yDiff when in non-flipped coordinates (like macOS's default)
            super.draw(in: context)
            context.restoreGState()
        }
    }
    

提交回复
热议问题