2011-09-08 2 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

관련 문제