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

假如想象 提交于 2019-12-09 20:08:24

问题


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);

}

}

来源:https://stackoverflow.com/questions/20689475/textkit-custom-text-attribute-draws-big-rect-when-it-spans-multiple-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!