指定矩形中的动态CCLabelTTF字体大小 - cocos2d

时间:2014-02-26 00:20:30

标签: ios cocos2d-iphone

我正在尝试创建一个由x,y,w和h指定的文本框,它可以接受任何字符串并将字体大小调整为尽可能大并且仍然适合框。我一直在尝试几种方法,但它不太有用。这是我最接近的尝试:

+ (CCLabelTTF*) wrap_text :(id)not_self :(NSString *)label :(double)x :(double)y :    (double)w :(double)h :(float) fontScale :(ccColor3B) color_front
{
    CGSize size;
    size = [[CCDirector sharedDirector] winSize];
    int boxWidth = (w - x) * size.width;
    int boxHeight = (h - y) * size.height;
    double middleX = ((w-x)/2 + x);
    double middleY = (1 - y);
    middleX *= size.width;
    middleY *= size.height;

    //float font_size = size.height * h * fontScale;
    int font_min = 5;
    int font_max = 300;
    int font_size = 5;
    int font_size_final = -1;
    int max_interations = 10;
    int i;

    NSString *hello = label;
    UIFont *font = [UIFont fontWithName:GLOBAL_FONT size:font_size];
    CGSize realSize = [hello sizeWithFont:font constrainedToSize:CGSizeMake(boxWidth, boxHeight) lineBreakMode:UILineBreakModeWordWrap ];

    i = 0;
    while ( true ) {
        if(realSize.width < boxWidth && realSize.height < boxHeight){
            //we found a good value, let's record it and try to go bigger
            font_size_final = font_size;
            font_min = font_size;
            font_size = (font_max - font_min) / 2 + font_min;
        }else if(realSize.width > boxWidth || realSize.height > boxHeight){
            //too big, let's try a smaller font
            font_max = font_size;
            font_size = (font_max - font_min) / 2 + font_min;
        }

        if(font_max == font_min || i >= max_interations)
            break;

        font = [UIFont fontWithName:GLOBAL_FONT size:font_size];
        realSize = [hello sizeWithFont:font constrainedToSize:CGSizeMake(boxWidth, boxHeight) lineBreakMode:UILineBreakModeWordWrap ];
        i++;
    }

    G_label = [CCLabelTTF labelWithString:label fontName:GLOBAL_FONT fontSize:font_size dimensions:CGSizeMake(boxWidth, boxHeight) hAlignment:UITextAlignmentCenter];
    G_label.color = color_front;
    G_label.anchorPoint = ccp(0.5f, 1);
    G_label.position = ccp( middleX , middleY );
    [not_self addChild:G_label];

    return G_label;
}

如果我将boxWidth和boxHeight更改为200,我会得到稍微好一些的结果,但我不明白为什么,它仍然不完美。有人能告诉我在哪里误入歧途吗?感谢。

1 个答案:

答案 0 :(得分:3)

* 此答案不是我的:原始答案发布在此处 - https://stackoverflow.com/a/9060833/1590951 以上帖子可归功于http://www.11pixel.com/blog/28/resize-multi-line-text-to-fit-uilabel-on-iphone/

我只是进行了一些小编辑,以便更容易在cocos2d中测试(在古老的cc2d 1.1上进行测试,所以如果你有不同的版本,则必须进行相关的编辑)

您可以尝试以下测试,看看这是否适合您的需求:

    NSString *fontString = @"Arial";
    CGSize targetSize = CGSizeMake(300.0f, 300.0f);
    int i;
    int fontSizeStep = 1;
    int fontSizeMin  = 6;
    int fontSizeMax  = 28;

    CCSprite *bg = [CCSprite spriteWithFile:@"Default.png"];
    [bg setScaleX: targetSize.width / bg.contentSize.width];
    [bg setScaleY: targetSize.height / bg.contentSize.height];
    [bg setPosition:ccp(s.width / 2.0f, s.height / 2.0f)];
    [bg setColor:ccc3(128, 128, 128)];
    [self addChild:bg];

    NSString *sampleText = @"Now the way that the book winds up is this: Tom and me found the money that the robbers hid in the cave, and it made us rich. We got six thousand dollars apiece -­ all gold. It was an awful sight of money when it was piled up. Well, Judge Thatcher he took it and put it out at interest, and it fetched us a dollar a day apiece all the year round -­ more than a body could tell what to do with. The Widow Douglas she took me for her son, and allowed she would sivilize me; but it was rough living in the house all the time, considering how dismal regular and decent the widow was in all her ways; and so when I couldn't stand it no longer I lit out. I got into my old rags and my sugar-hogshead again, and was free and satisfied. But Tom Sawyer he hunted me up and said he was going to start a band of robbers, and I might join if I would go back to the widow and be respectable. So I went back.";
//        NSString *sampleText = @"Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore— While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door— \"'Tis some visitor,\" I muttered, \"tapping at my chamber door— Only this and nothing more.";

    UIFont *font = [UIFont fontWithName:fontString size:fontSizeMax];
    /* Time to calculate the needed font size.
     This for loop starts at the largest font size, and decreases by two point sizes (i=i-2)
     Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */
    for(i = fontSizeMax; i > fontSizeMin; i-=fontSizeStep)
    {
        // Set the new font size.
        font = [font fontWithSize:i];

        // You can log the size you're trying: NSLog(@"Trying size: %u", i);
        /* This step is important: We make a constraint box
         using only the fixed WIDTH of the UILabel. The height will
         be checked later. */
        CGSize constraintSize = CGSizeMake(targetSize.width, MAXFLOAT);

        // This step checks how tall the label would be with the desired font.
        CGSize labelSize = [sampleText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:CCLineBreakModeWordWrap];

        /* Here is where you use the height requirement!
         Set the value in the if statement to the height of your UILabel
         If the label fits into your required height, it will break the loop
         and use that font size. */
        if(labelSize.height <= targetSize.height)
        {
            NSLog(@"Break on: %u", i);
            break;
        }
    }

    if(i == fontSizeMin)
    {
        NSLog(@"* possibly truncated text *");
    }

    // You can see what size the function is using by outputting: NSLog(@"Best size is: %u", i);
    CCLabelTTF *label = [CCLabelTTF labelWithString:sampleText dimensions:targetSize alignment:CCTextAlignmentLeft fontName:fontString fontSize:i];
    [label setPosition:ccp(s.width / 2.0f, s.height / 2.0f)];
    [self addChild:label];