Faking Subpixel Antialiasing on Text with Core Animation

前端 未结 5 1127
半阙折子戏
半阙折子戏 2020-12-08 02:58

For anyone working on a project with Core Animation layer-backed views, it\'s unfortunately obvious that subpixel antialiasing (text smoothing) is disabled for text not rend

5条回答
  •  Happy的楠姐
    2020-12-08 03:05

    If you are simply trying to get sharp looking text to display on an opaque background and hitting your head against the wall with CATextLayer - give up and use NSTextField with the inset disabled and linefragmentpadding set to 0. Sample code is swift but you should be able to translate easily...

    var testV = NSTextView()
    testV.backgroundColor = NSColor(calibratedRed: 0.73, green: 0.84, blue: 0.89, alpha: 1)
    testV.frame = CGRectMake(120.0, 100.0, 200.0, 30.0)
    testV.string = "Hello World!"
    testV.textContainerInset = NSZeroSize
    testV.textContainer!.lineFragmentPadding = 0
    self.addSubview(testV)
    

    for me displays text the equivalent to:

    var testL = CATextLayer()
    testL.backgroundColor = NSColor(calibratedRed: 0.73, green: 0.84, blue: 0.89, alpha: 1).CGColor
    testL.bounds = CGRectMake(0.0, 0.0, 200.0, 30.0)
    testL.position = CGPointMake(100.0, 100.0)
    testL.string = "Hello World!"
    testL.fontSize = 14
    testL.foregroundColor = NSColor.blackColor().CGColor
    self.layer!.addSublayer(testL)
    

    This class obviously comes with more overhead and possibly unnecessary things like text selecting/copying etc, but hey the text displays well.

提交回复
热议问题