how to resize an image or done as a NSAttributedString NSTextAttachment (or set its initital size)

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

I have a NSAttributedString to which I am adding a NSTextAttachment. The image is 50w by 50h but I'd like it to scale down to reflect the line height of the attributed string. I thought this would be done automatically but I guess not. I have looked at the UImage class reference but this image doesn't seem to be set in a UIImageView so no access to a frame property. Here's a screenshot of what I currently have:

In an ideal world, I would also like to implement a way to scale up the image based upon user input (such as increasing the font size). Any ideas on how to achieve this?

thx

edit 1

here's how I'm creating it:

    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];     textAttachment.image = [UIImage imageNamed:@"note-small.png"];     NSLog(@"here is the scale: %f", textAttachment.image.scale);     NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];     [headerAS replaceCharactersInRange:NSMakeRange([headerAS length], 0) withString:@" "];     [headerAS replaceCharactersInRange:NSMakeRange([headerAS length], 0) withAttributedString:attrStringWithImage]; 

回答1:

Look at subclassing NSTextAttachment and implementing the NSTextAttachmentContainer methods to return different sizes based on the text container supplied. By default, NSTextAttachment just returns the size of the image it is provided with.



回答2:

You should set bounds form attachment to resize image like this:

attachment.bounds = CGRectMake(0, 0, yourImgWidth, yourImgHeight);



回答3:

If you need to resize a bunch of NSTextAttachment images while keeping their aspect ratio i've written a handy extension: http://hack.swic.name/convenient-nstextattachment-image-resizing

extension NSTextAttachment {     func setImageHeight(height: CGFloat) {         guard let image = image else { return }         let ratio = image.size.width / image.size.height          bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: ratio * height, height: height)     } } 

Example usage:

let textAttachment = NSTextAttachment() textAttachment.image = UIImage(named: "Image") textAttachment.setImageHeight(16) // Whatever you need to match your font  let imageString = NSAttributedString(attachment: textAttachment) yourAttributedString.appendAttributedString(imageString) 


回答4:

NSTextAtatchment is just a holder for a UIImage so scale the image when it needs scaling and recreate the text attachment or set it's image. You'll need to force a nslayout update if you change the image on an existing text attachment.



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