OSTextAttachment (iOS)

OSTextAttachment.h

@interface OSTextAttachment : NSTextAttachment

@end

OSTextAttachment.m

@implementation OSTextAttachment

- (id)initWithData:(NSData *)contentData ofType:(NSString *)uti {
    //FLOG(@"initWithData called");
    //FLOG(@"uti is %@", uti);
    self = [super initWithData:contentData ofType:uti];
    
    if (self) {
        if (self.image == nil) {
            //FLOG(@" self.image is nil");
            self.image = [UIImage imageWithData:contentData];
        } else {
            FLOG(@" self.image is NOT nil");
        }
    }
    return self;
}

- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex {
    
    //FLOG(@"attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex: called");
    float width = lineFrag.size.width;
    
    return [self scaleImageSizeToWidth:width];
}

// Scale the image to fit the line width less 10%
- (CGRect)scaleImageSizeToWidth:(float)width {
    
    float scalingFactor = 1.0;
    
    CGSize imageSize = [self.image size];
    
    if (width < imageSize.width)
        scalingFactor = (width*0.9) / imageSize.width;
    
    CGRect rect = CGRectMake(0, 0, imageSize.width * scalingFactor, imageSize.height * scalingFactor);
    
    return rect;
    
}
@end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s