2013-07-10 73 views
0

當我draw這些textPDFtruncatespecific width這兩個區別我不明白。這兩個CGContextShowTextAtPoint的區別?

第一個

NSString *strText12 = @"HASDHADH skjdfhhs HKSJDHF.;; []'.hfkjhsfS SDHJHFSH jsfsjdfsn eiwj NJSDSJDF SDLKJJ sfkjsj wreoiwuowu 87243 7298 72jsdj [email protected]#[email protected]$$"; 

if (strText12.length > 110) { 
    strText12 = [strText12 substringToIndex:110]; 
    strText12 = [strText12 stringByAppendingFormat:@"...."]; 
} 

CGContextSelectFont (aCgPDFContextRef, "Helvetica", 12, kCGEncodingMacRoman); 
CGContextSetTextDrawingMode (aCgPDFContextRef, kCGTextFill); 
CGContextSetRGBFillColor (aCgPDFContextRef, 0, 0, 0, 1); 
const char *text1 = [strText12 UTF8String]; 
CGContextShowTextAtPoint (aCgPDFContextRef, 10,50.0, text1, strlen(text1)); 

第二個

NSString *strText = @"hasdhadh skjdfhhs hksjdhf.;; []'.hfkjhsfs sdhjhfsh jsfsjdfsn eiwj njsdsjdf sdlkjj sfkjsj wreoiwuowu 87243 7298 72jsdj [email protected]#[email protected]$$"; 

if (strText.length > 110) { 
    strText = [strText substringToIndex:110]; 
    strText = [strText stringByAppendingFormat:@"...."]; 
} 

CGContextSelectFont (aCgPDFContextRef, "Helvetica", 12, kCGEncodingMacRoman); 
CGContextSetTextDrawingMode (aCgPDFContextRef, kCGTextFill); 
CGContextSetRGBFillColor (aCgPDFContextRef, 0, 0, 0, 1); 
const char *text = [strText UTF8String]; 
CGContextShowTextAtPoint (aCgPDFContextRef, 10,10.0, text, strlen(text)); 

結果在PDF

enter image description here

編輯:即使使用CoreTextresult也是same

+0

我不明白這個問題。您將兩個字符串截斷爲110 *個字符*。大寫字母「HASDHADH」比*小寫字母「hasdhadh」寬*,因此第一個字符串需要更多空間。 –

+0

如何能夠截斷字符串到特定的寬度與依賴字符串可能在OSX中的任何情況下的字母? –

回答

0

一種解決方案可以是:從actual string獲取的upperCase lettersno和計數的現在proportionally 35乘法%將從original index被移除,其爲110。

NSString *textToDraw = some string 
int range = 100; 
NSString *strTruncate = textToDraw; 
if (strTruncate.length > range) { 
    strTruncate = [strTruncate substringToIndex:range]; 

    //NSLog(@"now : %@",strTruncate); 

    int actualIndex = 0; 
    int count = [self getNoUpperCaseCharWithString:strTruncate]; 
    if (count>0) { 
     float minusIndex = (float)count*0.35; 
     actualIndex = range - (int)minusIndex; 
     //actualIndex -= 4; 
    } 
    else{ 
     actualIndex = range; 
    } 

    if (strTruncate.length > actualIndex) { 
     textToDraw = [strTruncate substringToIndex:actualIndex]; 
     textToDraw = [strTruncate stringByAppendingFormat:@"..."]; 
    } 

    //NSLog(@"after : %@",textToDraw); 
} 

獲取的upperCase字母countstring

-(int)getNoUpperCaseCharWithString:(NSString *)string 
{ 
    int count=0; 
    for (int i = 0; i < [string length]; i++) { 
    BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[string characterAtIndex:i]]; 
    if (isUppercase == YES) 
     count++; 
    } 
    return count; 
} 

EDIT:not found accur吃了這些解決方案.......