在图像视图图像上写文本

时间:2012-11-14 10:27:40

标签: iphone uiimageview uiimage ios6

目前,我正在开发一个应用程序,其中我有一个图像视图,其中图像始终是

一段时间后会发生变化。现在我希望我能够写一些文字或绘制任何符号

,简单的线条,十字线意味着在图像视图中显示图像上的绘图。意味着我想

在图像上添加文字或绘制一些符号或线条e.t.c.我到处搜索但不能

找到任何解决方案。我怎么解决这个问题?提前谢谢。

2 个答案:

答案 0 :(得分:2)

您有两种选择。

  1. 添加UILabel作为imageView的子视图,并将UILabel的backgroundcolor设置为清除颜色。
  2. 实现以下方法,该方法将图像和文本作为参数并返回文本添加图像。

    //将文字添加到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];
    
    }
    
  3. 参考:http://iphonesdksnippets.com/post/2009/05/05/Add-text-to-image-%28UIImage%29.aspx

答案 1 :(得分:1)

看看是否有效:

//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];

}
相关问题