Re: text highlighting with CALayer and NSTextVew
Re: text highlighting with CALayer and NSTextVew
- Subject: Re: text highlighting with CALayer and NSTextVew
- From: Koen van der Drift <email@hidden>
- Date: Sat, 25 Aug 2012 06:10:29 -0400
On Aug 24, 2012, at 11:28 PM, Koen van der Drift <email@hidden> wrote:
>
> On Aug 24, 2012, at 12:23 PM, Kyle Sluder <email@hidden> wrote:
>
>> Sorry, I did in fact mean -[NSView convertRectToLayer:] and -convertRectToBacking:. As well as the point-based conversion methods.
>
> That's too bad, I guess I'll need to look for an alternative.
>
> BTW, is there a way to move a CALayer when the window resizes? Or should I just recalculate it?
>
> - Koen.
>
So what I am basically trying to do here is to highlight certain strings in an NSTextView that match a pattern. I am using CALayers for the highlighting since that gives me more control of the drawing.
When the text is small, the drawing is pretty quickly, but when I have a larger piece of text, especially when I scroll, the drawing and scrolling is very slow, probably because it is constantly recalculating. The code below is called from the NSTextView drawRect:
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern: myRegexPattern options:0 error:&error];
[regularExpression enumerateMatchesInString: [self string]
options: 0
range: NSMakeRange(0, [[self string] length])
usingBlock: ^(NSTextCheckingResult *match,
NSMatchingFlags flags, BOOL *stop)
{
NSRange aRange;
NSUInteger rectCount;
NSRange selectedRange = NSMakeRange(NSNotFound, 0);
NSRect layerRect;
aRange = [match range];
NSRectArray rectArray = [[self layoutManager] rectArrayForCharacterRange: aRange
withinSelectedCharacterRange: selectedRange
inTextContainer: [self textContainer]
rectCount: &rectCount];
layerRect = rectArray[0];
layerRect.size.height -= 9;
layerRect.size.width -= 1;
CALayer *aLayer = [CALayer layer];
aLayer.frame = [self convertRectToLayer: layerRect];
aLayer.borderColor = CGColorCreateGenericRGB (0.20f, 0.20f, 0.20f, 1.0f);
aLayer.backgroundColor = CGColorCreateGenericRGB (0.20f, 0.20f, 0.20f, 0.5f);
aLayer.borderWidth = 1.0f;
aLayer.masksToBounds = YES;
aLayer.cornerRadius = 2.0f;
[self.layer addSublayer: aLayer];
}];
What would be a good strategy to optimize this code for drawing? Calculating the NSIntersect of the NSRect passed in by drawRect: and layerRect helps a bit, but again when scrolling there is a delay when drawing the highlighted strings.
Thanks,
- Koen.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden