2012-03-02 32 views
7

Ngay từ cái nhìn đầu tiên, câu hỏi của tôi trông rất đơn giản, nhưng có vẻ như tôi thực sự không thể tìm ra giải pháp. Đây là nội dung: Tôi muốn tính toán hộp giới hạn của chuỗi CATextLayer. Dưới đây là những gì tôi làm:Cách tính toán hộp giới hạn của chuỗi 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); 

Vấn đề là đầu ra luôn là: (chiều rộng, chiều cao) = (8.000000,0.000000)

Trả lời

7

Sử dụng sizeWithFont:constrainedToSize:lineBreakMode:

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

// sử dụng dưới hàm cho CATextLayer động

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) 
    } 
} 
Các vấn đề liên quan