Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
Jasarien Avatar asked Dec 21 '10 11:12

Jasarien


2 Answers

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.

like image 64
Jasarien Avatar answered Oct 16 '22 19:10

Jasarien


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];
like image 27
DenVog Avatar answered Oct 16 '22 18:10

DenVog