2011-09-08 28 views
1

此代碼無效,我不明白這個錯誤。 請幫忙。如何寫入UIImage?

-(UIImage *)addText:(UIImage *)img text:(NSString *)text1 
    {  
     int w = img.size.width; 
     int h = img.size.height; 
     //lon = h - lon; 
     char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding]; 
     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

     /*UIGraphicsBeginImageContext(self.view.bounds.size); 
     [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
     CGContextShowTextAtPoint(UIGraphicsGetCurrentContext(), 50, 100, text, strlen(text)); 
     UIImage *viewImage =UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
     NSLog(@"View Image : %@",viewImage);*/ 

     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, 50, text, strlen(text)); 
     CGContextSetTextMatrix(context, CGAffineTransformMakeRotation(-M_PI/4)); 
     CGContextShowTextAtPoint(context, 50, 100, text, strlen(text)); 
     //UIImage *compositeImage = UIGraphicsGetImageFromCurrentImageContext(); 
     CGImageRef imageMasked = CGBitmapContextCreateImage(context); 
     CGContextRelease(context); 
     CGColorSpaceRelease(colorSpace); 
     NSLog(@"Image : %@",[UIImage imageWithCGImage:imageMasked]); 

     return [UIImage imageWithCGImage:imageMasked]; 
     //return viewImage; 
    } 
+5

我建議更好的格式,簡化和什麼是應該做的更好的解釋。 – Bemmu

+0

我認爲這個代碼對於它應該做什麼來說是自我解釋的。 – Robin

回答

6

除非你有充分的理由來避免的NSString UIKit的增加,這將足夠了:

+(UIImage*) drawText:(NSString*) text 
      inImage:(UIImage*) image 
      atPoint:(CGPoint) point 
       font:(UIFont*) font 
       color:(UIColor*) color 
{ 
    UIGraphicsBeginImageContextWithOptions(image.size, FALSE, 0.0); 
    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; 
    CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); 
    [color set]; 
    [text drawInRect:CGRectIntegral(rect) withFont:font]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext(); 

    return newImage; 
} 
0

您的代碼確實有效。

確保您傳入的字符串不爲空。

+0

Yah字符串肯定不是空的。 –

+0

也許您傳遞的圖像太小,您無法看到結果。你的代碼確實有效。 – cmlloyd