0

我想创建文本的 UIImage。是否有任何可以帮助我的教程。我阅读了很多博客,但所有博客都显示了如何在 uiimage 上创建文本,但我需要书面文本的 uimage。如果有人对此有任何想法,请帮助我。非常感谢。

4

2 回答 2

1

嗨,你试试这个……我希望它对你有用

-(UIImage *)imageFromText:(NSString *)text withImage:(UIImage*)img{
   // set the font type and size
   UIFont *font = [UIFont systemFontOfSize:100.0];  
   CGSize size  = [text sizeWithFont:font];

   // check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
   if (UIGraphicsBeginImageContextWithOptions != NULL)
       UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
   else
       // iOS is < 4.0 
       UIGraphicsBeginImageContext(size);

   // optional: add a shadow, to avoid clipping the shadow you should make the context size bigger 
   //
   CGContextRef ctx = UIGraphicsGetCurrentContext();
   CGContextSetShadowWithColor(ctx, CGSizeMake(0.0, 1.0), 5.0, [[UIColor blackColor] CGColor]);
   CGContextSetBlendMode(ctx,kCGBlendModeNormal);
//   CGContextSetFillColorWithColor(ctx, [UIColor whiteColor].CGColor);

    CGContextSetFillColorWithColor(ctx, [UIColor colorWithPatternImage:img].CGColor);


   /*NSLog(@"Rect  %@",CGContextGetClipBoundingBox(ctx));
    CGImageRef alphaMask = CGBitmapContextCreateImage(ctx);
    CGContextClipToMask(ctx, CGContextGetClipBoundingBox(ctx), alphaMask);*/


   // draw in context, you can use also drawInRect:withFont:
   [text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];

   // transfer image
   UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();    

   return image;
}

方法调用将是...

[self imageFromText:@"Booooooooom"];
于 2012-08-30T07:55:28.720 回答
0

检查这段代码,应该可以工作。您可以在函数内自由更改某些参数。请注意,您必须将在其他地方创建的 UIImage 传递给此方法。

//Add text to UIImage
-(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
    CGContextSetTextMatrix(context, CGAffineTransformMakeRotation( -M_PI/4 ));

    CGContextShowTextAtPoint(context, 4, 52, text, strlen(text));


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

    return [UIImage imageWithCGImage:imageMasked];
}
于 2012-08-30T07:54:12.810 回答