vertically align text in a CATextLayer?

后端 未结 15 1364
时光说笑
时光说笑 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:21

    gbk's code works. below is gbk's code updated for XCode 8 beta 6. Current as of 1 Oct 2016

    Step 1. Subclass CATextLayer. In the code below I've named the subclass "MyCATextLayer" Outside your view controller class copy/paste the below code.

    class MyCATextLayer: CATextLayer {
    
    // REF: http://lists.apple.com/archives/quartz-dev/2008/Aug/msg00016.html
    // CREDIT: David Hoerl - https://github.com/dhoerl
    // USAGE: To fix the vertical alignment issue that currently exists within the CATextLayer class. Change made to the yDiff calculation.
    
    override init() {
        super.init()
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(layer: aDecoder)
    }
    
    override func draw(in ctx: CGContext) {
        let height = self.bounds.size.height
        let fontSize = self.fontSize
        let yDiff = (height-fontSize)/2 - fontSize/10
    
        ctx.saveGState()
        ctx.translateBy(x: 0.0, y: yDiff)
        super.draw(in: ctx)
        ctx.restoreGState()
       }
    }
    

    Step 2. Within your view controller class in your ".swift" file, create your CATextLabel. In the code example I've named the subclass "MyDopeCATextLayer."

    let MyDopeCATextLayer: MyCATextLayer = MyCATextLayer()
    

    Step 3. Set your new CATextLayer with desired text/color/bounds/frame.

    MyDopeCATextLayer.string = "Hello World"    // displayed text
    MyDopeCATextLayer.foregroundColor = UIColor.purple.cgColor //color of text is purple
    MyDopeCATextLayer.frame = CGRect(x: 0, y:0, width: self.frame.width, height: self.frame.height)  
    MyDopeCATextLayer.font = UIFont(name: "HelveticaNeue-UltraLight", size: 5) //5 is ignored, set actual font size using  ".fontSize" (below)
    MyDopeCATextLayer.fontSize = 24
    MyDopeCATextLayer.alignmentMode = kCAAlignmentCenter //Horizontally centers text.  text is automatically centered vertically because it's set in subclass code
    MyDopeCATextLayer.contentsScale = UIScreen.main.scale  //sets "resolution" to whatever the device is using (prevents fuzzyness/blurryness)
    

    Step 4. done

提交回复
热议问题