textkit custom text attribute draws big rect when it spans multiple lines

964 views Asked by At

I am basically creating a custom attribute to draw a rounded rectangle in my text subclassing NSLayoutManager with drawGlyphsForGlyphRange method below. Below works like a charm with ranges that spans one line. However, when the range of text spans in two lines, I am getting a big rectangle which draws the attribute along those two lines. I think I should be using a different approach here, I tried nsbackgroundattribute to draw the highlight but unfortunately I cannot make the highlight rounded rect using that.

I would appreciate any directions.

-(void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origin {

NSTextStorage *textStorage = self.textStorage;
NSRange glyphRange = glyphsToShow;
while (glyphRange.length > 0) {
   NSRange charRange = [self characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL], attributeCharRange, attributeGlyphRange;
   id attribute = [textStorage attribute:IKSpecialHighlightAttributeName atIndex:charRange.location longestEffectiveRange:&attributeCharRange inRange:charRange];

    attributeGlyphRange = [self glyphRangeForCharacterRange:attributeCharRange actualCharacterRange:NULL];

    attributeGlyphRange = NSIntersectionRange(attributeGlyphRange, glyphRange);

    if( attribute != nil ) {



        NSTextContainer *textContainer = self.textContainers[0];

        CGRect boundingRect = [self boundingRectForGlyphRange:attributeGlyphRange inTextContainer:textContainer];





        [[UIColor colorWithRed:221.0/255.0 green:255.0/255.0 blue:0.0/255.0 alpha:1] setFill]; // set rounded rect's bg color



        boundingRect.origin.x += origin.x-3.0;

        boundingRect.origin.y += origin.y+3.0;

        boundingRect.size.width += 6.0;



        UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:boundingRect cornerRadius: 3.0];



        [roundedRect fillWithBlendMode: kCGBlendModeNormal alpha:1.0f];




        [super drawGlyphsForGlyphRange:attributeGlyphRange atPoint:origin];

    }

    else {

        [super drawGlyphsForGlyphRange:glyphsToShow atPoint:origin];

    }

    glyphRange.length = NSMaxRange(glyphRange) - NSMaxRange(attributeGlyphRange);

    glyphRange.location = NSMaxRange(attributeGlyphRange);

}

}

0

There are 0 answers