可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.