Ios 下划线文本-不同字体大小的交叉范围中的线条粗细

Ios 下划线文本-不同字体大小的交叉范围中的线条粗细,ios,uitextview,nsattributedstring,textkit,Ios,Uitextview,Nsattributedstring,Textkit,我正在使用UITextView的textStorage属性。我有我的类textformatingelement的字符串和对象数组。此类的实例包括NSRange(必须在其上以文本形式应用此元素)和一些格式参数: @interface TextFormattingElement : NSObject @property (nonatomic) NSRange range; @property (nonatomic, strong) NSString *fontName; //e.g. @"Ti

我正在使用
UITextView
的textStorage属性。我有我的类
textformatingelement
的字符串和对象数组。此类的实例包括
NSRange
(必须在其上以文本形式应用此元素)和一些格式参数:

@interface TextFormattingElement : NSObject

@property (nonatomic) NSRange range;
@property (nonatomic, strong) NSString *fontName;   //e.g. @"TimesNewRomanPSMT"
@property (nonatomic) int fontSize;
@property (nonatomic, strong) UIColor *fontColor;
@property (nonatomic) BOOL isBold;
@property (nonatomic) BOOL isItalic;
@property (nonatomic) BOOL isUnderlined;
@property (nonatomic) BOOL isStriked;

@end
现在我循环遍历这个数组,并将这些元素依次应用到textView的textStorage。我使用这种方法:

-(void)setFontWithName:(NSString*)name AndSize:(float)fontSize AndTextColor:(UIColor*)textColor AndIsBold:(BOOL)isBold AndIsItalic:(BOOL)isItalic AndIsUnderlined:(BOOL)isUnderLined andIsStriked:(BOOL)isStriked ToRange:(NSRange)rangeToSet{
   __block UIFont *font = [UIFont fontWithName:name size:fontSize];
   __block UIFontDescriptor *fontDescriptor = [font fontDescriptor];

   [textView.textStorage enumerateAttributesInRange:rangeToSet options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
      NSParagraphStyle *paragraphStyle = [attrs objectForKey:NSParagraphStyleAttributeName];

      NSMutableDictionary *attributesToSetDict = [NSMutableDictionary dictionary];
     [attributesToSetDict setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];  //i need to clear all attributes at this range exсept NSParagraphStyleAttributeName

      if(isBold){
          uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitBold;
          fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
      }

      if(isItalic){
          uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | UIFontDescriptorTraitItalic;
          fontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
      }

      font = [UIFont fontWithDescriptor:fontDescriptor size:fontSize];
      [attributesToSetDict setObject:font forKey:NSFontAttributeName];
      [attributesToSetDict setObject:textColor forKey:NSForegroundColorAttributeName];

      if(isUnderLined){
          [attributesToSetDict setObject:@1 forKey:NSUnderlineStyleAttributeName];
      }

      if(isStriked){
          //TODO: isStriked
      }

      [textView.textStorage setAttributes:attributesToSetDict range:range];
    }];
  }
我有一个问题:如果我有两个具有交叉范围的
textformatingelement
实例(例如
NSMakeRange(9,28)
NSMakeRange(26,7)
),下划线的厚度始终与最后一个元素的字体大小有关。您可以在该屏幕截图中看到这方面的说明:

my 2格式元素的参数为:

1st:location=9,length=28,fontName=TimesNewRomanPSMT,fontSize=15,fontColor=UIDeviceGBColorSpace 1 0 0 1,isBold=0,isTalic=0,is下划线=1,isStriked=0

2nd:location=26,length=7,fontName=timesnewromapsmt,fontSize=25,fontColor=UIDeviceGBColorSpace 0 0 1,isBold=1,isTalic=0,is下划线=1,isStriked=0

但我想得到谷歌文档中的效果:


如何使用TextKit实现这一点?

在iOS 7上,您可以使用覆盖
-DrawUnderlineForglypRange:underlineType:baselineOffset:lineFragmentRect:lineFragmentGlyphRange:containerOrigin:
一个创建文本系统对象并绘制所需下划线的小示例

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];

    // setup text handling with our subclass of NSLayoutManager
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:@"Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do;"];

    MyLayoutManager *textLayout = [[MyLayoutManager alloc] init];

    [textStorage addLayoutManager:textLayout];

    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.view.bounds.size];

    [textLayout addTextContainer:textContainer];
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0,20,self.view.bounds.size.width,self.view.bounds.size.height-20)
                                               textContainer:textContainer];
    [self.view addSubview:textView];

    // setup test attributes
    UIFont *font = [UIFont fontWithName:@"TimesNewRomanPSMT" size:15];

    NSMutableDictionary *attributesToSetDict = [NSMutableDictionary dictionary];

    [attributesToSetDict setObject:font forKey:NSFontAttributeName];
    [attributesToSetDict setObject:[UIColor blueColor] forKey:NSForegroundColorAttributeName];
    [attributesToSetDict setObject:@1 forKey:NSUnderlineStyleAttributeName];

    [textView.textStorage setAttributes:attributesToSetDict range:NSMakeRange(9, 28)];

    UIFontDescriptor *fontDescriptor = [font fontDescriptor];
    attributesToSetDict = [NSMutableDictionary dictionary];
    [attributesToSetDict setObject:[UIFont fontWithDescriptor:fontDescriptor size:25] forKey:NSFontAttributeName];
    [attributesToSetDict setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
    [attributesToSetDict setObject:@1 forKey:NSUnderlineStyleAttributeName];

    [textView.textStorage setAttributes:attributesToSetDict range:NSMakeRange(26, 7)];
}
@end

@implementation MyLayoutManager
- (void)drawUnderlineForGlyphRange:(NSRange)glyphRange underlineType:(NSUnderlineStyle)underlineVal baselineOffset:(CGFloat)baselineOffset lineFragmentRect:(CGRect)lineRect lineFragmentGlyphRange:(NSRange)lineGlyphRange containerOrigin:(CGPoint)containerOrigin
{
    /* For the sample we consider that underlineVal is equals to NSUnderlineStyleSingle */

    /*
     * We need to create a CTFontRef as UIFont doesn't provided 'Underline Position' and 'Underline Thickness'
     */

    // get current UIFont for the glyphRange
    NSRange characterRange = [self characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL];
    UIFont *font = [[self.textStorage attributesAtIndex:characterRange.location effectiveRange:NULL] objectForKey:NSFontAttributeName];

    CTFontRef ctfont = CTFontCreateWithName((CFStringRef)[font fontName], [font pointSize], NULL);

    CGPoint startLocation = [self locationForGlyphAtIndex:glyphRange.location];
    CGPoint endLocation = [self locationForGlyphAtIndex:NSMaxRange(glyphRange)];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // -underlineGlyphRange:underlineType:lineFragmentRect:lineFragmentGlyphRange:containerOrigin: already set color and line width
    // for the current context

    // reset line width with current font underline thickness
    CGContextSetLineWidth(ctx, CTFontGetUnderlineThickness(ctfont));

    CGContextMoveToPoint(ctx, startLocation.x + containerOrigin.x, startLocation.y + containerOrigin.y - CTFontGetUnderlinePosition(ctfont));
    CGContextAddLineToPoint(ctx, endLocation.x + containerOrigin.x, endLocation.y + containerOrigin.y - CTFontGetUnderlinePosition(ctfont));

    CGContextStrokePath(ctx);

    CFRelease(ctfont);
}

谢谢!我也开始朝这个方向努力,但在从字符中找到下划线厚度和下划线缩进的公式时遇到了问题。现在有了你的答案,我知道如何使用核心文本。万分感谢你!!!