【发布时间】:2012-04-16 16:16:25
【问题描述】:
我正在尝试将文本转换为图像并将该图像用作子视图。但是我得到了一些错误。我从另一个 stackoverflow 帖子中得到了这段脚本;
/* Creates an image with a home-grown graphics context, burns the supplied string into it. */
- (UIImage *)burnTextIntoImage:(NSString *)text :(UIImage *)img {
UIGraphicsBeginImageContext(img.size);
CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height);
[img drawInRect:aRectangle];
[[UIColor redColor] set]; // set text color
NSInteger fontSize = 14;
if ( [text length] > 200 ) {
fontSize = 10;
}
UIFont *font = [UIFont boldSystemFontOfSize: fontSize]; // set text font
[ text drawInRect : aRectangle // render the text
withFont : font
lineBreakMode : UILineBreakModeTailTruncation // clip overflow from end of last line
alignment : UITextAlignmentCenter ];
UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext(); // extract the image
UIGraphicsEndImageContext(); // clean up the context.
return theImage;
}
我用代码来调用这段代码:
[self burnTextIntoImage:textInsert :textImage];
我得到的错误是:
<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
<Error>: CGContextSetFont: invalid context 0x0
<Error>: CGContextSetTextMatrix: invalid context 0x0
<Error>: CGContextSetFontSize: invalid context 0x0
<Error>: CGContextSetTextPosition: invalid context 0x0
<Error>: CGContextShowGlyphsWithAdvances: invalid context 0x0
【问题讨论】:
-
这是一个奇怪的方法名称。从它的名字来看,我希望图像参数是第一个,文本参数是第二个。你确定不是不小心把它们弄混了?您如何真正调用该方法?您问题中的调用行将很难编译。
-
那你觉得我应该怎么调用这个方法呢?我只是使用上面写的一个,其中 textInsert 是一个带有我要编译的文本的 nsstring,而 textImage 是一个 UIImage,我用它来显示编译后的文本图像。
-
在方法名称中,每个冒号前面的单词(或多个单词)通常表示冒号后面的参数类型。所以一个好名字应该是
(UIImage *)burnText: (NSString*)text intoImage:(UIImage *)image。 (顺便说一句:在第四次查看调用行之后,我发现我可能错了,它编译了。你的方法名称对我来说太混乱了。) -
我改了,还是不行。我得到和以前一样的错误。
-
贴出的代码没有明显的错误。所以问题可能是
img参数是nil(你检查过这个)或者你没有在主线程上运行代码。
标签: iphone objective-c ios xcode cgcontext