2012-03-02 2 views
7

첫눈에 제 질문은 정말 간단 해 보이지만 해결책을 찾지 못하는 것 같습니다. 다음은 같습니다 : CATextLayer의 문자열 경계 상자를 계산하고 싶습니다. 여기 내가 할 것입니다 :CATextLayer 문자열의 경계 상자를 계산하는 방법은 무엇입니까?

CATextLayer *textLayer = [CATextLayer layer]; 
textLayer.frame = CGRectMake(80, 0.0f, 36.0f, 18.0f); 
textLayer.string = @"12"; 
textLayer.fontSize = [UIFont systemFontSize]; 
textLayer.foregroundColor = [UIColor whiteColor].CGColor; 

NSLog(@"(width,height)=(%f,%f)", 
[textLayer.string sizeWithFont:textLayer.font].width, 
[textLayer.string sizeWithFont:textLayer.font].height); 

문제는 출력이 항상 있다는 것입니다 : (폭, 높이) = (8.000000,0.000000)

답변

7

사용 sizeWithFont:constrainedToSize:lineBreakMode:

[someString sizeWithFont:yourFont 
     constrainedToSize:CGSizeMake(maxWidthYouSpecify, CGFLOAT_MAX) 
      lineBreakMode:UILineBreakModeWordWrap]; 
1

동적 CATextLayer 펑션 아래 사용 //

func DynamicLableWidth(reason:NSString,cpT:CGPoint,width:CGFloat,reasonLayer:CATextLayer) 
{ 

    //Dynamic CATextLayer with boundingRect 
    let font = UIFont(name: "Arial", size: 20)! 
    let attributes: [NSString : AnyObject] = [NSFontAttributeName: font] 

    var rect:CGRect = reason.boundingRectWithSize(reasonLayer.frame.size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil) 

    var size:CGSize = CGSizeMake(rect.size.width, rect.size.height); 
    if cpT.x+20+ceil(size.width)+20>width 
    { 
     reasonLayer.frame = CGRectMake(cpT.x-20-ceil(size.width)+20, cpT.y-15, ceil(size.width)+20, 20) 
    } 
    else 
    { 
     reasonLayer.frame = CGRectMake(cpT.x+20, cpT.y-15, rect.size.width+20, 20) 
    } 
} 
관련 문제