tim*_*one 23 uiimage nsattributedstring nstextattachment ios ios7
我有一个NSAttributedString我要添加一个NSTextAttachment.图像是50w乘50h,但我希望它缩小以反映属性字符串的行高.我以为这会自动完成,但我猜不会.我查看了UImage类引用,但是这个图像似乎没有在UIImageView中设置,因此无法访问框架属性.这是我目前拥有的截图:
在理想的世界中,我还想实现一种基于用户输入(例如增加字体大小)来放大图像的方法.关于如何实现这一点的任何想法?
谢谢
这是我如何创建它:
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];
Run Code Online (Sandbox Code Playgroud)
Dun*_*yen 43
您应该设置边界表单附件以调整图像大小,如下所示:
attachment.bounds = CGRectMake(0, 0, yourImgWidth, yourImgHeight)
Mac*_*wic 25
如果您需要调整大量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)
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
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)
Run Code Online (Sandbox Code Playgroud)
Wai*_*ain 15
查看子类化NSTextAttachment
并实现NSTextAttachmentContainer
方法,以根据提供的文本容器返回不同的大小.默认情况下,NSTextAttachment
只返回其提供的图像的大小.
归档时间: |
|
查看次数: |
16384 次 |
最近记录: |