如何在UIImage中写一些带有特殊字符的文本?

时间:2011-08-23 11:16:49

标签: iphone ios text uiimage core-graphics

我想在UIImage中写一些文字,我发现这个link并且它有效,但是如果你试着写一些特殊字符,比如“á,é,í,ö,ô...... “那就失败了。

代码:

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

有什么想法可以解决这个问题吗?

谢谢。

修改

我试图改变:

char* text  = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];

char* text  = (char *)[text1 cStringUsingEncoding:NSUTF8StringEncoding];

但它不起作用。

2 个答案:

答案 0 :(得分:2)

另一位用户告诉我该怎么做:

-(UIImage *)writeText:(NSString *)text1 toImage:(UIImage *)img{

    CGSize sizeText = [text1 sizeWithFont:[UIFont fontWithName:@"Helvetica" size:36] minFontSize:36 actualFontSize:nil forWidth:783 lineBreakMode:UILineBreakModeTailTruncation];

    CGFloat posX = 1024.0 - 230.0 - sizeText.width;


    UIGraphicsBeginImageContextWithOptions(img.size, NO, 0.0f);
    [img drawAtPoint:CGPointMake(0.0f, 0.0f)];
    [text1 drawAtPoint:CGPointMake(posX, 588.0) withFont:[UIFont fontWithName:@"Helvetica" size:36]];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
} 

在此link

答案 1 :(得分:1)

尝试使用NSUTF8StringEncoding而不是NSASCIIStringEncoding