2012-03-02 9 views
7

A prima vista la mia domanda sembra davvero semplice, ma sembra che non riesca davvero a trovare una soluzione. Ecco cos'è: Voglio calcolare il riquadro di delimitazione della stringa di un CATextLayer. Ecco quello che faccio:Come calcolare il riquadro di delimitazione della stringa di un 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); 

Il problema è che l'uscita è sempre: (larghezza, altezza) = (8.000000,0.000000)

risposta

7

Usa sizeWithFont:constrainedToSize:lineBreakMode:

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

// usare sotto funzione per CATextLayer dinamica

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) 
    } 
} 
Problemi correlati