如何调整图像大小或完成NSAttributedString NSTextAttachment(或设置其初始大小)

我有一个NSAttributedString我添加一个NSTextAttachment。 图像是50瓦50小时,但我想它缩小以反映属性string的行高度。 我以为这会自动完成,但我猜不是。 我已经看了UImage类的引用,但这个图像似乎并没有在UIImageView中设置,所以没有访问框架属性。 以下是我目前拥有的截图:

在这里输入图像说明

在一个理想的世界里,我还想实现一种基于用户input(例如增加字体大小)来放大图像的方式。 任何想法如何实现这一目标?

谢谢

编辑1

这是我如何创build它:

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]; 

查看NSTextAttachment子类并实现NSTextAttachmentContainer方法,根据提供的文本容器返回不同的大小。 默认情况下, NSTextAttachment只是返回它提供的图像的大小。

你应该设置边界表单附件来调整图像的大小,像这样:

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

如果你需要调整一堆NSTextAttachment图像的大小,同时保持它们的宽高比,我写了一个方便的扩展: 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) } } 

用法示例:

 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) 

NSTextAtatchment只是UIImage的一个持有者,因此在需要缩放和重新创build文本附件或设置图片时,可以缩放图片。 如果您更改现有文本附件上的图像,则需要强制执行nslayout更新。