Setting the background colour/highlight colour for a given string range using Core Text
Asked Answered
O

2

8

I have some text laid out using Core Text in my iPhone app. I'm using NSAttributedString to set certain styles within the text for given ranges.

I can't seem to find an attribute for setting a background / highlight colour, though it would seem it is possible. I couldn't find an attribute name constant that sounded relevant and the documentation only lists:

kCTCharacterShapeAttributeName
kCTFontAttributeName
kCTKernAttributeName
kCTLigatureAttributeName
kCTForegroundColorAttributeName
kCTForegroundColorFromContextAttributeName
kCTParagraphStyleAttributeName
kCTStrokeWidthAttributeName
kCTStrokeColorAttributeName
kCTSuperscriptAttributeName
kCTUnderlineColorAttributeName
kCTUnderlineStyleAttributeName
kCTVerticalFormsAttributeName
kCTGlyphInfoAttributeName
kCTRunDelegateAttributeName

Craig Hockenberry, developer of Twitterrific has said publicly on Twitter that he uses Core Text to render the tweets, and Twitterrific has this background / highlight that I'm talking about when you touch a link.

alt text

Any help or pointers in the right direction would be fantastic, thanks.

Edit: Here's a link to the tweet Craig posted mentioning "Core text, attributed strings and a lot of hard work", and the follow up that mentioned using CTFrameSetter metrics to work out if touches intersect with links.

Oxytocic answered 21/12, 2010 at 11:48 Comment(1)
This is not an answer but can you use the screenshot option in the Organiser window of XCode or does that cancel touches as well?Robet
O
3

In the end, I had to use the Core Text metrics methods (getting the range, bounds, origins of lines etc) to calculate the bounding rectangle of the link. Once I had a rect for each line the link spanned, I drew the background into the context before redrawing the text above it.

Seems like a hell of a lot of work, but it works.

Oxytocic answered 28/12, 2010 at 12:49 Comment(4)
Hi Jasarien, Can you show how to use those metrics?.I am very new to core text.It will be very helpful. I am trying on my own too.Aubrette
Try this quick presentation, it's very useful. slideshare.net/DJune/text-layout-with-core-textOxytocic
I think it would be nicer if you provided the solution you found.Skewness
The solution I ended up with is here github.com/jasarien/CoreTextHyperlinkViewOxytocic
G
1

With iOS 6, I think you can get the effect you're looking for with: NSBackgroundColorAttributeName. Such as:

[attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:selectedRange];
Gleason answered 5/12, 2012 at 22:25 Comment(2)
This does not draw any BackgroundColor when using CTFrameDraw and CTFramesetterCreateFrameDanforth
I don't think this attribute has a equal attribute for CTAttributedStringWakeless

© 2022 - 2024 — McMap. All rights reserved.