2012-09-19 61 views
0

我想在CGRect的底部畫一個NSString。到目前爲止,我已經能夠將文本置於頂部居中,但我需要將其置於底部。我也試過DrawAtPoint,但沒有奏效。這是我目前擁有的代碼: UIGraphicsBeginImageContext(img.size);在CGRect中繪製NSString

CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height); 
[img drawInRect:aRectangle]; 

[[UIColor whiteColor] set]; 
NSInteger fontSize = 25; 
UIFont *font = [UIFont boldSystemFontOfSize: fontSize]; 

[text drawInRect:aRectangle withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter]; 



UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

回答

0

可以使用方法: sizeWithFont:constrainedToSize:lineBreakMode 獲取文本大小,然後計算左上角點並使用drawAtPoint繪製文本

+0

我試圖用drawAtPoint視圖倍,但由於某種原因,它不加入在矩形的頂部繪製。 –

+0

你也可以drawInRect,但矩形尺寸計算sizeWithFont:constrainedToSize:lineBreakMode – blackmilk

+0

這是我的整個代碼,所以你可以更好地瞭解我在做什麼。 –

0

使用此方法:

-(UIImage *)imageFromText:(NSString *)text 
{ 
    CGSize maximumSize = CGSizeMake(300, 1000); //set width for string to wrap. 
    UIFont *font = [UIFont boldSystemFontOfSize:16]; 
    CGSize strSize = [text sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap]; 
    if (UIGraphicsBeginImageContextWithOptions != NULL) 
    UIGraphicsBeginImageContextWithOptions(strSize,NO,0.0); 
    else 
    // iOS is < 4.0 
    UIGraphicsBeginImageContext(strSize); 

    CGRect newframe = CGRectMake(0, 0, strSize.width, strSize.height); 
    [text drawInRect:newframe 
        withFont:font 
      lineBreakMode:UILineBreakModeWordWrap 
       alignment:UITextAlignmentLeft]; 
    UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext();  
    return testImg; 
} 
+0

我嘗試使用您的代碼,但返回的圖像只是黑色。我嘗試添加[[UIColor whiteColor]集合];將文本顏色設置爲白色,但不起作用。 –

+0

現在檢查...... –

+0

它仍然是全黑的... –

0

我發現這段代碼對我的問題非常有幫助。

- (UIImage *)addText:(UIImage *)img text:(NSString *)text1{ 
    int w = img.size.width; 
    int h = img.size.height; 
    //lon = h - lon; 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); 

    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage); 
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1); 

    char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];// "05/05/09"; 
    CGContextSelectFont(context, "Arial", 18, kCGEncodingMacRoman); 
    CGContextSetTextDrawingMode(context, kCGTextFill); 
    CGContextSetRGBFillColor(context, 255, 255, 255, 1); 


    //rotate text 
    CGContextShowTextAtPoint(context, 0, 5, text, strlen(text)); 


    CGImageRef imageMasked = CGBitmapContextCreateImage(context); 
    CGContextRelease(context); 
    CGColorSpaceRelease(colorSpace); 

    return [UIImage imageWithCGImage:imageMasked]; 
}