Post

Replies

Boosts

Views

Activity

Reply to What is the designated way to do custom background drawing in TextKit 2 when using UITextView/NSTextView?
I ran into the same issue. I'm doing something different – writing my own custom Text View instead of using NSTextView – but you may be able to make use of similar techniques. My goal was to: Fix Text Kit 2's lackluster background color rendering (comparison screenshots of TextEdit in Ventura and Monterey attached; FB10541687). Be able to draw the selection in front of the background color but behind the text (FB10542426). The steps are Make a custom NSAttributeString.Key for "undrawnBackgroundColor" Implement NSTextContentStorageDelegate.textContentStorage(_:textParagraphWith:) and return a custom NSTextParagraph with all occurrences of the .backgroundColor attribute replaced by .undrawnBackgroundColor. This prevents NSTextLayoutFragment.draw(at:in:) from drawing the background color. In NSTextViewportLayoutControllerDelegate.textViewportLayoutController(_:configureRenderingSurfaceFor:) create a layer for the layout fragment, and then create N layers for each of the background color frames. You get the attributed string from the layout fragment's textElement (an NSTextParagraph), use NSAttributedString.enumerateAttribute(_:in:) to get all the runs that contain background colors, and then for each of those runs, use NSTextLayoutManager.enumerateTextSegments(in:type:options:using:) to enumerate the frames for each of your background color layers. If you use .highlight or .selection (no idea what the difference is, they seem to have all the same drawing rules) as the type in enumerateTextSegments(in:type:options:using:), you'll get the nicer background color drawing behavior seen in Monterey's TextEdit (which still uses TextKit 1 for Rich Text).
Jul ’22