2009-10-30 41 views
6

Cách thêm văn bản vào hình ảnh và hiển thị dưới dạng một hình ảnh. Iam chọn hình ảnh từ Thư viện ảnh và sau đó viết văn bản lên đó và muốn lưu dưới dạng một hình ảnh? Để bất kỳ ai biết được ai sẽ xử lý nó?Thêm văn bản vào UIImage

Trả lời

6

Tôi đã sử dụng đoạn mã sau để thêm một văn bản để UIImage, hy vọng nó sẽ giúp

UIImage *img = [self drawText:@"Your String" 
           inImage:[UIImage imageNamed:@"empty_image.png"] 
           atPoint:CGPointMake(15, 25)]; 



-(UIImage*) drawText:(NSString*) text 
      inImage:(UIImage*) image 
      atPoint:(CGPoint) point 
{ 

    NSMutableAttributedString *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy]; 
    textStyle = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",text]]; 

    // text color 
    [textStyle addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, textStyle.length)]; 

    // text font 
    [textStyle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, textStyle.length)]; 

    UIGraphicsBeginImageContext(image.size); 
    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; 
    CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); 
    [[UIColor whiteColor] set]; 

    // add text onto the image 
    [textStyle drawInRect:CGRectIntegral(rect)]; 

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

    return newImage; 
} 
Các vấn đề liên quan