翻转NSTextAttachment的图像

时间:2018-04-04 11:14:14

标签: objective-c nstextattachment

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
NSImage *image = [NSImage imageNamed:@"emotion"];;
attachment.image = image;
NSAttributedString *attributedString = [NSAttributedString  attributedStringWithAttachment: attachment];
[[_feedbackContent textStorage] appendAttributedString:attributedString];

将图像添加到NSTextAttachment后,它是垂直翻转的。任何人都知道如何解决这个问题。

3 个答案:

答案 0 :(得分:3)

NSTextAttachment似乎使用NSFileWrapper文件名来获取UTI,并且根据UTI具有不同的行为。

我可以使用NSFileWrapper来修复它:

NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:data];
// Without a filename (which is used to get the UTI by NSTextAttachment)
// the image is displayed flipped.
[fileWrapper setPreferredFilename:@"Attachment.png"];
NSTextAttachment  *attachment = [[NSTextAttachment alloc] initWithFileWrapper:fileWrapper];

您也可以尝试将fileType属性设置为kUTTypePNG或其他图像类型,以使其正常工作。

radar:// 47170950

答案 1 :(得分:1)

当绘制成翻转视图时(这就是图像被翻转的原因),我发现的唯一解决方法是创建翻转图像,然后再绘制:

textAttachment.image = [NSImage imageWithSize:image.size flipped:YES drawingHandler:^BOOL(NSRect dstRect) {
    [image drawInRect:dstRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
    return YES;
}];

答案 2 :(得分:0)

将图像分配给NSTextAttachmentCell,而不是NSTextAttachment。

id <NSTextAttachmentCell> cell = [[NSTextAttachmentCell alloc] initImageCell:image];

NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
[attachment setAttachmentCell:cell];