5

As others have done, I'm trying to get decent looking text on a CALayer backed view. The most relevant thread I've found is Faking Subpixel Antialiasing on Text with Core Animation.

At the start of that post, it's stated that "Now, for people who are able to set opaque backgrounds for their text (either with a setBackgroundColor: call or the equivalent setting in Interface Builder), this issue doesn't present too much of a problem." However, when I set the background of a text box in IB, and have it draw the background, and do the same with its cell, I'm still getting the same problem (no antialiasing when layers are used). These belong to a NSBox that also draws its background.

Any idea as to what I should be doing that I'm not? Thanks

Community
  • 1
  • 1
pickwick
  • 3,134
  • 22
  • 30

2 Answers2

3

Not sure if this helps solve your problem, but when you do custom drawing in a layer, you have to use CGContextFillRect() with an opaque color and then draw the string on top of that rect to get subpixel antaialiasing.

Setting layer.backgroundColor is not good enough, probably because layer.backgroundColor can be changed without re-drawing the layer contents.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
  • do you have an example of how you would draw the string such that it doesn't render poorly - my attempt did not render nicely. – Sam Feb 12 '15 at 16:43
  • @Sam make sure you set the `layer.contentsScale` to `[UIScreen mainScreen].scale`. – Abhi Beckert Feb 14 '15 at 01:54
  • Beautiful. This worked perfectly. I had been setting layer.backgroundColor to a fully opaque color, but I was not filling that color before drawing the text. As soon as I did, the text rendered perfectly. Thanks! – Bryan Mar 18 '16 at 04:52
0

If you are simply trying to get sharp looking text 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)
James Alvarez
  • 7,159
  • 6
  • 31
  • 46