CTFrameGetVisibleStringRange еквивалент за програмиране на iOS?

Имам нужда от метод като CTFrameGetVisibleStringRange, който може да ми даде текста, който ще бъде изобразен в даден размер, предоставен с режим за прекъсване на ред (т.е. пренасяне на думи). Например имам дълъг ред от текст... и имам даден правоъгълник, за да нарисувам текста, обвит в него, но където и да бъде съкратен текстът, продължавам да го изобразявам в друга област, където е спрял. Така че имам нужда от метод като:

NSString * text = "The lazy fox jumped over the creek";
[text drawAtPoint:CGPointMake(0, 0) forWidth:20 withFont:[UIFont fontWithName:@"Arial" size:10] lineBreakMode:UILineBreakModeWordWrap];
// now I do I know how much it drew before it stopped rendering?

Някой има ли идеи?

**РЕДАКТИРАНО: Моля, вижте моето решение.


person Mike S    schedule 20.03.2011    source източник


Отговори (3)


Имах подобен проблем и използвах решението, публикувано от Майк.

Оказа се обаче, че trimToWord често ми дава няколко твърде много думи, отколкото можеха да се поберат в определения от мен размер на UILabel. Открих, че ако променя оператора на цикъла while на >=, а не само на >, той работи перфектно.

Добавих също няколко ivars(chopIndex и remainingBody), които използвах, за да получа оставащия низ, за ​​да мога да го покажа в следващия си UILabel.

Ето решението, което използвах.

-(NSString*) rewindOneWord:(NSString*) str{
    // rewind by one word
    NSRange lastspace = [str rangeOfString:@" " options:NSBackwardsSearch];
    if (lastspace.location != NSNotFound){
        int amount = [str length]-lastspace.location;
        chopIndex -= amount;
        return [str substringToIndex:lastspace.location];
    }else {
        // no spaces, lets just rewind 2 characters at a time
        chopIndex -= 2;
        return [str substringToIndex:[str length]-2];
    }
}

// returns only how much text it could render with the given stipulations   
-(NSString*) trimToWord:(NSString*)str sizeConstraints:(CGSize)availableSize withFont:(UIFont*)font{
    if(str == @"")
        return str;

    CGSize measured = [str sizeWithFont:font constrainedToSize:CGSizeMake(availableSize.width, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
    // 'guess' how much we will need to cut to save on processing time
    float choppedPercent = (((double)availableSize.height)/((double)measured.height));
    if(choppedPercent >= 1.0){
        //entire string can fit in availableSize
        remainingBody = @"";
        return str;
    }

    chopIndex = choppedPercent*((double)[str length]);
    str = [str substringToIndex:chopIndex];
    // rewind to the beginning of the word in case we are in the middle of one
    do{
        str = [self rewindOneWord:str];
        measured = [str sizeWithFont:font constrainedToSize:availableSize lineBreakMode:UILineBreakModeWordWrap];
    }while(measured.height>=availableSize.height);

    //increment past the last space in the chopIndex
    chopIndex++;

    //update the remaining string
    remainingBody = [remainingBody substringFromIndex:chopIndex];

    return str;
}
person teradyl    schedule 04.04.2011
comment
Наградих ви с отговора на този въпрос, тъй като подобрихте моето решение. Благодаря @teradyl - person Mike S; 15.05.2013

Ето едно решение. Това е доста бързо. Той „отгатва“ къде първо да накълца и след това се връща назад дума по дума. sizewithFont извикванията са доста скъпи, така че тази първоначална стъпка „предположение“ е важна. Основният метод е trimToWord: sizeConstraints:withFont.

Чувствайте се свободни да коментирате как мога да подобря това.

-(NSString*) rewindOneWord:(NSString*) str{
    // rewind by one word
    NSRange lastspace = [str rangeOfString:@" " options:NSBackwardsSearch];
    if (lastspace.location != NSNotFound){
        int amount = [str length]-lastspace.location;
        return [str substringToIndex:lastspace.location];
    }else {
        // no spaces, lets just rewind 2 characters at a time
        return [str substringToIndex:[str length]-2];
    }
}

// returns only how much text it could render with the given stipulations   
-(NSString*) trimToWord:(NSString*) str sizeConstraints:(CGSize) avail withFont:(UIFont*) font{
    CGSize measured = [str sizeWithFont:font constrainedToSize:CGSizeMake(avail.width, 1000000) lineBreakMode:UILineBreakModeWordWrap];
    // 'guess' how much we will need to cut to save on processing time
    float choppedPercent = (((double)avail.height)/((double)measured.height));
    if (choppedPercent >= 1.0){
        return str;
    }

    int chopIndex = choppedPercent*((double)[str length]);
    str = [str substringToIndex:chopIndex];
    // rewind to the beginning of the word in case we are in the middle of one
    str = [self rewindOneWord:str];
    measured = [str sizeWithFont:font constrainedToSize:avail lineBreakMode:UILineBreakModeWordWrap];
    while (measured.height>avail.height){
        str = [self rewindOneWord:str];
        measured = [str sizeWithFont:font constrainedToSize:avail lineBreakMode:UILineBreakModeWordWrap];
    }
    return str;
}
person Mike S    schedule 27.03.2011

Не мисля, че има заместител на CTFrameGetVisibleStringRange, въпреки че можем да получим същото с използването на метода по-долу.

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

Документация на Apple

http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html

РЕДАКТИРАНО: Кодът по-долу показва моя подход

NSString * text = "The lazy fox jumped over the creek";

NSArray* m_Array = [text  componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@" "]];

CGSize mySize = CGSizeMake(300,180);
NSMutableString* myString = [[NSMutableString alloc] initWithString:@""];

//The below code till the end of the while statement could be put in separate function.

CGSize tempSize = CGSizeMake(0,0);
NSInteger index = 0 ;
do
{
      [myString  appendString:[m_Array objectAtIndex:index]];
      tempSize  = [myString  sizeWithFont:myfont constrainedToSize: 
      CGSizeMake(mySize.width, CGFLOAT_MAX) lineBreakMode: UILineBreakModeWordWrap];
      index++;

}while(tempSize.height < mySize.height && index <= [m_Array count])

//Remove the string items from m_Array till the (index-1) index,

[self RemoveItems:m_Array tillIndex:(index-1)];//Plz define you own

//you have the myString which could be fitted in CGSizeMake(300,180);


//Now start with remaining Array items with the same way as we have done above.
}
person Jhaliya - Praveen Sharma    schedule 20.03.2011
comment
Това ми дава размер... Трябва да знам каква част от низа е начертана. - person Mike S; 20.03.2011
comment
@Mike Simmons: Точно така, като използвате тази функция, можете да проверите за минимална група думи, които да запълнят даден правоъгълник. - person Jhaliya - Praveen Sharma; 20.03.2011
comment
Харесва ми накъде сте се насочили с това решение, но myString завършва без интервали в него. Също така, дори ако добавите обратно знаците за интервал, това не позволява ситуации, при които има 2 знака за интервал между една дума. Имам нужда моят низ да бъде перфектно представяне на това, което беше преди. - person Mike S; 20.03.2011
comment
Освен това много бавно се извиква sizeWitFont отново и отново за всяка дума, затова се надявах, че има някакъв еквивалент на CTFrameGetVisibleStringRange в рамките на iOS. В настоящия момент единственото решение, което виждам за вашия код, е да преминете през символ по символ, което вероятно ще бъде 5 пъти по-бавно отново. - person Mike S; 20.03.2011
comment
забравям да добавя знака за интервал след [split objectAtIndex:index]]; - person Jhaliya - Praveen Sharma; 20.03.2011
comment
Моля, уведомете ме за резултата, може би трябва да направим повече промени, за да работи, - person Jhaliya - Praveen Sharma; 20.03.2011