ios - NSAttributedString 上的模糊图像 (NSTextAttachment)

标签 ios nsattributedstring

我正在使用 NSAttributedString 将图像包含在字符串中。然而,图像有时会模糊,就像在非整数框架上绘制一样。

我试图确保每个 NSTextAttachment 的边界都是整数大小,但这似乎没有帮助。有关如何确保它不模糊的任何提示?

见附件截图,第一辆公交车不模糊,但第二辆公交车模糊。

enter image description here

最佳答案

我通过在 NSAttributedString 上添加一个类别来解决这个问题。

基本上,您需要获取 NSTextAttachment 的框架并添加其 X 坐标缺少的小数部分以使其很好地四舍五入。

- (void)applyBlurrinessFixToAttachments {
    [self enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
        if (![value isKindOfClass:[NSTextAttachment class]]) {
            return;
        }
        NSTextAttachment *attachment = (NSTextAttachment*)value;
        CGRect bounds = attachment.bounds;
        CGRect attributedStringRect = [self boundingRectForCharacterRange:range];

        double integral;
        double fractional = modf(attributedStringRect.origin.x, &integral);
        if (fractional > 0) {
            double roundedXOrigin = 1.0 - fractional;

            // If X coordinate starts at 0.7, add 0.3 to it
            bounds.origin.x += roundedXOrigin;
            attachment.bounds = bounds;
        }
    }];
}

- (CGRect)boundingRectForCharacterRange:(NSRange)range {
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:self];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [textStorage addLayoutManager:layoutManager];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)];
textContainer.lineFragmentPadding = 0;
    [layoutManager addTextContainer:textContainer];

    NSRange glyphRange;
    [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];

    return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
}

关于ios - NSAttributedString 上的模糊图像 (NSTextAttachment),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27281945/

相关文章:

objective-c - 你如何抚摸 NSAttributedString 的_outside_?

ios - 将文本和图像放在 AttributedString 中

ios - UILabel 属性文本在开始新行之前不会填满整行

ios - 如何在AFNetworking的http 422响应上获取返回的对象?

ios - 在 iOS 上运行 ionic 3 时出错

android - 在 StackNavigator 中创建 DrawerNavigator

html - 如何将粗体和斜体字体应用于 NSAttributedString?

ios - 表格单元格中的突出显示模式

ios - 隐藏 UIButton 而不仅仅是移除可见性

c++ - IOS 删除 native 库中分配的内存