2014-03-03 2 views
0

정확한 너비로지도에 텍스트를 그리기 위해 올바른 글꼴 크기를 찾는 방법을 찾고 있습니다 (사용자가지도를 확대하거나 축소 할 때 변경됨). 나는 다음과 같은 코드를 사용하는 데 사용 :주어진 폭의 iOS 도면 텍스트

+(float) calulateHeightFromMaxWidth:(NSString*)text withMaxWidth:(float)maxWidth withMaxFontSize:(float)maxFontSize{ 
CGFloat fontSize; 

[text sizeWithFont:[UIFont systemFontOfSize:maxFontSize] minFontSize:1 actualFontSize:&fontSize forWidth:maxWidth lineBreakMode:NSLineBreakByTruncatingTail]; 

return fontSize; 

을}

항상 정답을 반환 그러나이 방법은 sizeWithFont는 아이폰 OS 7에 도시되어 난 후 그것을 주어진 글꼴 크기를 반환하는 교체를 찾을 수 없습니다 너비. 이 사이트에서 크기를 지정한 후에 너비를 알려줄 많은 게시물을 발견했지만 반대 (sizeWithAttributes :)를 찾을 수 없습니다. 나는이 방법이 100의 어쩌면 1000의 시간 끌기이라고 칭할 수 있던대로, 나가 적합하는 것을 찾아 낼 때까지 다른 글꼴 크기를 통해 반복을 포함하는 해결책을 피하는 것을 시도하고있다.

+0

가능한 중복 [와 내가되지 않는 sizeWithFont 교체해야하는지 : contrainedToSize : lineBreakMode 방법] (http://stackoverflow.com/questions/18315441/with-what-should-i-place-the-deprecated-sizewithfontcontrainedtosizelinebrea) – Austin

답변

0

보기 을 매개 변수 크기의 높이와 너비 모두에 전달하여 텍스트의 실제 크기를 얻을 수 있습니다.

편집 : 여기에 비 사용되지 않는 방법을 사용하여 매우 효율적으로 이상적인 글꼴 크기를 계산하는 코드는 다음과 같습니다

+(float) calulateHeightFromMaxWidth:(NSString*)text withMaxWidth:(float)maxWidth withMaxFontSize:(float)maxFontSize{ 

    // The less exact you try to match the width, the fewer times the method will need to be called 
    CGFloat textWidthMatchDelta = 10; 
    CGFloat fontSize = maxFontSize; 
    CGFloat minFontSize = 0; 
    // If drawing a single line of text, omit `|NSStringDrawingUsesLineFragmentOrigin`. 
    NSUInteger textOptions = NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin; 

    while (YES) { 
     CGRect textRect = [text boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) 
              options:textOptions 
              attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:fontSize] 
              context:nil]; 
     CGFloat textWidth = CGRectGetWidth(textRect); 

     if (textWidth > maxWidth) { 
      maxFontSize = fontSize; 
      fontSize /= 2.0f; 
     } else if (textWidth + textWidthMatchDelta < maxWidth) { 
      minFontSize = fontSize; 
      fontSize = minFontSize + (maxFontSize - minFontSize)/2.0f; 
     } else { 
      break; 
     } 
    } 

    return fontSize; 
} 
+0

감사합니다. 난 그냥 "NSStringDrawingUsesLineFragmentOrigin"당신이 한 줄을 그리기 제안대로 제거해야했습니다. – cerby87

관련 문제