밑줄 텍스트-글꼴 크기가 다른 교차 범위의 선 두께

xexe

textStorage의 속성으로 작업하고 UITextView있습니다. 내 클래스의 개체의 문자열과 배열이 TextFormattingElement있습니다. 이 클래스의 인스턴스는 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];
    }];
  }

한 가지 문제가 있습니다. TextFormattingElement교차 범위 (예 : NSMakeRange(9,28)NSMakeRange(26,7)) 가있는 두 인스턴스가 있는 경우 밑줄의 두께는 항상 마지막 요소의 글꼴 크기에 따라 달라지는 값을 갖습니다. 이 그림은이 스크린 샷에서 볼 수 있습니다.

여기에 이미지 설명 입력

내 두 가지 서식 지정 요소의 매개 변수는 다음과 같습니다.

첫 번째 : 위치 = 9, 길이 = 28, fontName = TimesNewRomanPSMT, fontSize = 15, fontColor = UIDeviceRGBColorSpace 10 0 1, isBold = 0, isItalic = 0, isUnderlined = 1, isStriked = 0

두 번째 : 위치 = 26, 길이 = 7, fontName = TimesNewRomanPSMT, fontSize = 25, fontColor = UIDeviceRGBColorSpace 012 1, isBold = 1, isItalic = 0, isUnderlined = 1, isStriked = 0

하지만 Google 문서에서와 같은 효과를 얻고 싶습니다.

여기에 이미지 설명 입력

TextKit을 사용하여 어떻게 할 수 있습니까?

엠마누엘

iOS 7에서는 텍스트 시스템 개체를 만들고 원하는 밑줄을 그리는 작은 샘플 NSLayoutManager재정 -drawUnderlineForGlyphRange: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);
}

견본

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

서로 다른 글꼴 크기의 두 부분 텍스트 아래쪽 정렬

분류에서Dev

텍스트가 각 줄에 서로 다른 글꼴 크기로 두 줄로 분산 된 부트 스트랩 버튼

분류에서Dev

재구성 된 텍스트의 다른 글꼴 크기

분류에서Dev

하나의 글꼴, 두 개의 텍스트, 다른 문자

분류에서Dev

jquery에서 선택한 텍스트의 글꼴 크기 조정

분류에서Dev

Swift에서 TextView 텍스트에 두 가지 다른 글꼴 크기를 추가하는 방법

분류에서Dev

큰 글꼴 크기의 경우 Javascript Marquee 텍스트가 잘립니다.

분류에서Dev

아이콘 글꼴 범위를 줄의 텍스트 범위와 정렬

분류에서Dev

uitextview의 글꼴 두께 가져 오기

분류에서Dev

텍스트 줄의 정확한 높이 (글꼴 크기 + 줄 높이)

분류에서Dev

다른 브라우저의 줄 높이와 글꼴 크기?

분류에서Dev

ggplot에서 텍스트 레이블의 다른 부분에 대한 다른 글꼴 크기

분류에서Dev

인용구 마크 업 후 텍스트에서 굵은 글꼴 두께를 제거 할 수 없습니다.

분류에서Dev

Debian wheezy의 두 가지 설치에서 다른 콘솔 글꼴 크기

분류에서Dev

자바 FX에서 같은 텍스트 행 내에서 두 개의 서로 다른 글꼴 크기를 할 수있는 방법이 있습니까?

분류에서Dev

가로 막 대형 차트의 "좌표 근처 노드"에서 글꼴 크기 줄이기 #tikzpicture #pgfplots

분류에서Dev

다른 줄의 글 리피 콘 및 텍스트 링크

분류에서Dev

글꼴 크기가 다양 할 때 UILabel의 텍스트를 동적으로 늘리거나 줄이는 방법 iOS

분류에서Dev

Google 차트 글꼴 크기가 작동하지 않습니다.

분류에서Dev

Unsemantic을 사용하여 두 개의 서로 다른 글꼴 크기를 한 줄에 배치하는 방법

분류에서Dev

Gimp는 텍스트 도구에서 굵게, 기울임 꼴, 밑줄, 취소 선 아이콘을 표시하지 않습니다.

분류에서Dev

조정 가능한 밑줄 두께와 글자와 밑줄 사이의 수직 공간이있는 CSS 여러 줄 링크

분류에서Dev

밑줄과 글꼴의 색상이 다릅니다.

분류에서Dev

텍스트에 큰 글꼴 크기로 노란색 밑줄이있는 이유는 무엇입니까?

분류에서Dev

Google 크롬 브라우저에서 jquery를 사용하여 iframe 태그 내에서 선택 / 강조 표시된 텍스트의 글꼴 크기를 늘리거나 줄입니다.

분류에서Dev

두 범위 사이의 교차 세트 찾기

분류에서Dev

CSS는 한 줄에 두 가지 글꼴 크기를 가져옵니다.

분류에서Dev

Android가 작동하지 않는 다운로드 가능한 글꼴의 글꼴 두께

분류에서Dev

Google 시각화 차트에서 특정 라벨의 글꼴 및 두께 변경

Related 관련 기사

  1. 1

    서로 다른 글꼴 크기의 두 부분 텍스트 아래쪽 정렬

  2. 2

    텍스트가 각 줄에 서로 다른 글꼴 크기로 두 줄로 분산 된 부트 스트랩 버튼

  3. 3

    재구성 된 텍스트의 다른 글꼴 크기

  4. 4

    하나의 글꼴, 두 개의 텍스트, 다른 문자

  5. 5

    jquery에서 선택한 텍스트의 글꼴 크기 조정

  6. 6

    Swift에서 TextView 텍스트에 두 가지 다른 글꼴 크기를 추가하는 방법

  7. 7

    큰 글꼴 크기의 경우 Javascript Marquee 텍스트가 잘립니다.

  8. 8

    아이콘 글꼴 범위를 줄의 텍스트 범위와 정렬

  9. 9

    uitextview의 글꼴 두께 가져 오기

  10. 10

    텍스트 줄의 정확한 높이 (글꼴 크기 + 줄 높이)

  11. 11

    다른 브라우저의 줄 높이와 글꼴 크기?

  12. 12

    ggplot에서 텍스트 레이블의 다른 부분에 대한 다른 글꼴 크기

  13. 13

    인용구 마크 업 후 텍스트에서 굵은 글꼴 두께를 제거 할 수 없습니다.

  14. 14

    Debian wheezy의 두 가지 설치에서 다른 콘솔 글꼴 크기

  15. 15

    자바 FX에서 같은 텍스트 행 내에서 두 개의 서로 다른 글꼴 크기를 할 수있는 방법이 있습니까?

  16. 16

    가로 막 대형 차트의 "좌표 근처 노드"에서 글꼴 크기 줄이기 #tikzpicture #pgfplots

  17. 17

    다른 줄의 글 리피 콘 및 텍스트 링크

  18. 18

    글꼴 크기가 다양 할 때 UILabel의 텍스트를 동적으로 늘리거나 줄이는 방법 iOS

  19. 19

    Google 차트 글꼴 크기가 작동하지 않습니다.

  20. 20

    Unsemantic을 사용하여 두 개의 서로 다른 글꼴 크기를 한 줄에 배치하는 방법

  21. 21

    Gimp는 텍스트 도구에서 굵게, 기울임 꼴, 밑줄, 취소 선 아이콘을 표시하지 않습니다.

  22. 22

    조정 가능한 밑줄 두께와 글자와 밑줄 사이의 수직 공간이있는 CSS 여러 줄 링크

  23. 23

    밑줄과 글꼴의 색상이 다릅니다.

  24. 24

    텍스트에 큰 글꼴 크기로 노란색 밑줄이있는 이유는 무엇입니까?

  25. 25

    Google 크롬 브라우저에서 jquery를 사용하여 iframe 태그 내에서 선택 / 강조 표시된 텍스트의 글꼴 크기를 늘리거나 줄입니다.

  26. 26

    두 범위 사이의 교차 세트 찾기

  27. 27

    CSS는 한 줄에 두 가지 글꼴 크기를 가져옵니다.

  28. 28

    Android가 작동하지 않는 다운로드 가능한 글꼴의 글꼴 두께

  29. 29

    Google 시각화 차트에서 특정 라벨의 글꼴 및 두께 변경

뜨겁다태그

보관