Search code examples
iosswiftcore-text

Disable blending when drawing with CoreText


I'm drawing black text on a gray background using CoreText. It seems that the system automatically does some blending on the glyphs, i'd like to disable this behavior if possible but I'm not sure how.

this is a zoomed-in screenshot of the top of the letter L. this is the blending i'd like to disable

enter image description here

The drawing code looks like:

let para = NSMutableParagraphStyle()
    para.alignment = .center

    let attrString = NSAttributedString(string: Configuration.trainString,
                                        attributes:  [
                                            .font:UIFont.boldSystemFont(ofSize: size.height*0.8),
                                            .paragraphStyle:para
        ])

    let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)

    let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil)

    CTFrameDraw(frame, ctx)

    let cgImage = ctx.makeImage()

    return cgImage

is there a way to do this while still leveraging CoreText?

EDIT: it is possible this is related, however I believe this question is still valid. this question can be answered explicitly with code, whereas no code was provided before. I am already rounding the path used by the framesetter to integrals (as well as the font size)

a full gist of the code that will run in a Swift playground is posted HERE


Solution

  • This may seem obvious, but it bears worth repeating that CTFrameDraw(_:_:) is ultimately just performing operations on CGContext so its text functions are essential.

    Depending on the specifics of what you want I suggest you experiment with the font smoothing functions on CGContext starting with setAllowsFontSmoothing(_:).

    EDIT

    Using your playground I found a specific solution. Add setAllowsAntialiasing just before drawing your text:

    ctx.setAllowsAntialiasing(false)
    CTFrameDraw(frame, ctx)