Change size of NSTextAttachment Image?

99封情书 提交于 2019-12-01 10:50:48

You can iterate over your NSAttributedString, get the attachments, the bounds and modify them:

[myAtrrString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, myAtrrString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
   if (![value isKindOfClass:[NSTextAttachment class]]) {
      return;
   }
   NSTextAttachment *attachment = (NSTextAttachment*)value;
    CGRect bounds = attachment.bounds;
   // modify bounds
   attachment.bounds = bounds;
}];

you can set the bounds of NSTextAttachment, for example(in Swift3):

        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: "info.png")
        attachment.bounds = CGRect(x: 5, y: -2, width: 15, height: 15)
        let attachmentString = NSAttributedString(attachment: attachment)


        let attributedString = NSMutableAttributedString(string: "My String")
        attributedString.append(attachmentString)
        labelText.attributedText = attributedString

Here is my solution.May be will help someone.

[yourSting enumerateAttribute:NSAttachmentAttributeName
                            inRange:NSMakeRange(0, [yourSting length])
                            options:0
                         usingBlock:^(id value, NSRange range, BOOL *stop)
             {
                 
                 if ([value isKindOfClass:[NSTextAttachment class]])
                 {
                     NSTextAttachment *attachment = (NSTextAttachment *)value;
                     UIImage *image = nil;
                     if ([attachment image])
                         image = [attachment image];
                     else
                         image = [attachment imageForBounds:[attachment bounds]
                                              textContainer:nil
                                             characterIndex:range.location];
                     
                     CGSize size = image.size;
                     if(size.width > kSCREEN_WIDTH - 10){

                         // calculate proportional height to width
                         float ratio = image.size.width /( kSCREEN_WIDTH -10);
                         float height = image.size.height / ratio;
                        
                         size = CGSizeMake(kSCREEN_WIDTH - 10, height);
                         
                         attachment.bounds = CGRectMake(0, 0, size.width, size.height);
                         attachment.image = image;
                                                
                     }
                 }
                 
             }]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!