【问题标题】:Kerning in iOS7/8 UITextView when using an NSAttributedString built from HTML使用从 HTML 构建的 NSAttributedString 时 iOS7/8 UITextView 中的字距调整
【发布时间】:2014-11-15 11:41:59
【问题描述】:

我无法在 iOS 7 和 8 上的 UITextView 内进行字距调整。当我直接设置字符串或使用手动构造的 NSAttributedString 时,字距调整工作正常,但当我从 HTML 生成 NSAttributedString。

以下代码将正确调整文本:

self.textView.attributedText = [[NSAttributedString alloc] initWithString:@"Test"];

但以下不是:

NSString *html = @"<html><head><style>\
                  body { font-size: 40px; text-rendering: optimizeLegibility; }\
                  </style></head>\
                  <body>Test</body></html>";
NSAttributedString *attrString = [[NSAttributedString alloc]
              initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]
              options:@{
                  NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                  NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
              }
              documentAttributes:nil error:nil];
self.textView.attributedText = attrString;

我做错了什么?

【问题讨论】:

    标签: ios nsattributedstring kerning


    【解决方案1】:

    当生成NSAttributedString 并且设置了NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType 选项时,iOS 将NSKern = 0 属性添加到属性字符串。您可以通过简单地记录属性字符串来检查这一点:

    Test{
        NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
        NSFont = "<UICTFont: 0x7fa470451e90> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 40.00pt";
        NSKern = 0;
        NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
        NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
        NSStrokeWidth = 0;
    }
    

    要解决此问题,只需完全删除 NSKern 属性:

    NSMutableAttributedString *mutableAttributedString = [attrString mutableCopy];
    [mutableAttributedString removeAttribute:NSKernAttributeName 
                                       range:NSMakeRange(0, [mutableAttrString length])];
    

    请注意,text-rendering: optimizeLegibility; 似乎没有任何影响,因此可以省略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-25
      • 2014-01-26
      • 1970-01-01
      • 2014-10-10
      • 2014-01-18
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      相关资源
      最近更新 更多