NSTextAttachment绑定NSAttributedString后图片垂直翻转问题求助
解决NSTextAttachment中图片垂直翻转的问题
这个问题我之前也碰到过!根源在于macOS里NSImage和文本布局的坐标系不匹配:NSImage的原点在左下角,而NSTextAttachment渲染时用的是类似UIKit的坐标系(原点在左上角),直接绑定图片就会出现垂直翻转的情况。
给你几个实用的解决办法:
方法一:调整NSTextAttachment的bounds偏移
最简单的方式,不需要修改图片本身,直接通过调整bounds的y值来修正位置:
NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; NSImage *image = [NSImage imageNamed:@"emotion"]; // 将图片向上偏移自身高度,抵消坐标系差异 attachment.bounds = CGRectMake(0, -image.size.height, image.size.width, image.size.height); attachment.image = image; NSAttributedString *attributedString = [NSAttributedString attributedStringWithAttachment: attachment]; [[_feedbackContent textStorage] appendAttributedString:attributedString];
方法二:创建翻转后的NSImage实例
如果需要保留原始图片,或者要复用翻转后的图片,可以手动绘制一个翻转版本:
NSImage *originalImage = [NSImage imageNamed:@"emotion"]; NSImage *flippedImage = [[NSImage alloc] initWithSize:originalImage.size]; [flippedImage lockFocus]; // 创建翻转变换 NSAffineTransform *flipTransform = [NSAffineTransform transform]; [flipTransform scaleXBy:1.0 yBy:-1.0]; [flipTransform translateXBy:0.0 yBy:-originalImage.size.height]; [flipTransform concat]; // 绘制原始图片到新图片中 [originalImage drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositingOperationCopy fraction:1.0]; [flippedImage unlockFocus]; // 绑定到NSTextAttachment NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; attachment.image = flippedImage; NSAttributedString *attributedString = [NSAttributedString attributedStringWithAttachment:attachment]; [[_feedbackContent textStorage] appendAttributedString:attributedString];
方法三:利用NSImage的快捷翻转方法
NSImage自带flippedImage方法可以直接获取垂直翻转后的图片,不过部分场景下可能需要配合bounds微调,保险起见还是推荐前两种方法:
NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; NSImage *image = [[NSImage imageNamed:@"emotion"] flippedImage]; attachment.image = image; NSAttributedString *attributedString = [NSAttributedString attributedStringWithAttachment: attachment]; [[_feedbackContent textStorage] appendAttributedString:attributedString];
选哪种看你的需求,方法一最快捷,方法二更灵活可控~
内容的提问来源于stack exchange,提问作者jimwan
相关产品推荐
相关产品推荐

