2

I am trying to make a text editor using UITextView in ios7 and above, but I am facing some terrible bugs. I have gone through many Stack Overflow questions related to scrolling of textview. But the main issue about which I am not able to find is slow rendering of text after adding NSTextAttachment(Custom) to it. I am using the approach described on this post:

http://ossh.com.au/design-and-technology/software-development/implementing-rich-text-with-images-on-os-x-and-ios/

But after adding the images the typing of text becomes terribly slow. The code is almost the same as described in the post so I have not pasted it here. The reason can be as said in the following question: ios - iOS 7 UITextView is slow after typing lots of text

"drawGlyphsForGlyphRange runs N*2 times, where N is the number of times your lines word-wrapped."

But I am not sure. Any advice in a direction to solve this terribly slow rendering of text?

Community
  • 1
  • 1
nick28
  • 134
  • 2
  • 7

1 Answers1

1

I have solved the lag by scaling the images when adding using the following code

-(void)insertImage:(UIImage *)image
{
NSTextAttachment* attachment = [[NSTextAttachment alloc] initWithData:UIImageJPEGRepresentation(image, 0.0) ofType:@"image/jpeg"];

    float scalingFactor = 1.0;

    CGSize imageSize = [image size];
    float width = self.frame.size.width;
    if (width < imageSize.width)
        scalingFactor = (width)*scalingFactor / imageSize.width;

    CGRect rect = CGRectMake(0, 0, imageSize.width*scalingFactor, imageSize.height *scalingFactor);
    attachment.image = [self imageWithImage:image scaledToSize:rect.size];
    attachment.bounds = [self scaleImageSizeToWidth:self.frame.size.width withImage:image];
    NSRange range = [self selectedRange];
    NSAttributedString* attachmentchar =
    [NSAttributedString attributedStringWithAttachment:attachment];
    [[self textStorage] insertAttributedString:attachmentchar atIndex:range.location];

}

I noticed using the - (void)textStorage:(NSTextStorage *)textStorage willProcessEditing:(NSTextStorageEditActions)editedMask range:(NSRange)editedRange changeInLength:(NSInteger)delta and enumerating the text storage for attachments and replacing them with custom nstextattachment subclass is not productive and is slowing down the rendering a lot.

nick28
  • 134
  • 2
  • 7
  • 1
    This approach is replacing the original pasted image with one that is scaled so any time you try using this attributed string on another device you will have potentially lost the original image quality. Depending on your requirements you could probably still go the custom attachment route here (rather than in willProcessEditing) but keep the original image as well as an image scaled for the device. A bit like a thumbnail. Drawback here is increased storage, but images scaled for iPhone as pretty small so not likely to be a big issue - well maybe not for retina. – Duncan Groenewald Apr 28 '14 at 20:36