我正在尝试将文本转换为图片并将该图片用作子视图。但是我收到了一些错误。我从另一个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
先谢谢!
答案 0 :(得分:0)
////Drawing text using Quartz 2D in an iOS application
- (void)drawRect:(CGRect)rect
{
CGContextRef theContext = UIGraphicsGetCurrentContext();
CGRect viewBounds = self.bounds;
CGContextTranslateCTM(theContext, 0, viewBounds.size.height);
CGContextScaleCTM(theContext, 1, -1);
// Draw the text using the MyDrawText function
MyDrawText(theContext, viewBounds);
}
////Drawing text
void MyDrawText (CGContextRef myContext, CGRect contextRect) // 1
{
float w, h;
w = contextRect.size.width;
h = contextRect.size.height;
CGAffineTransform myTextTransform; // 2
CGContextSelectFont (myContext, // 3
"Helvetica-Bold",
h/10,
kCGEncodingMacRoman);
CGContextSetCharacterSpacing (myContext, 10); // 4
CGContextSetTextDrawingMode (myContext, kCGTextFillStroke); // 5
CGContextSetRGBFillColor (myContext, 0, 1, 0, .5); // 6
CGContextSetRGBStrokeColor (myContext, 0, 0, 1, 1); // 7
myTextTransform = CGAffineTransformMakeRotation (MyRadians (45)); // 8
CGContextSetTextMatrix (myContext, myTextTransform); // 9
CGContextShowTextAtPoint (myContext, 40, 0, "Quartz 2D", 9); // 10
UIImage *theImage= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
更多访问以下链接...
希望,这会帮助你......冷静......
答案 1 :(得分:0)
<Error>: CGContextSetFillColorWithColor: invalid context 0x0
...
没有活动的图形上下文。 IOW,您正在请求抽奖,但没有运营商或目的地。
当本地存在图形上下文时(例如,调用drawRect:
时),您需要执行此调用,或者必须为流程明确创建上下文(例如CGBitmapContextCreate
)。
如果你正在使用UIGraphicsBeginImageContext
,那应该仅来自主线程。您可以使用任何主题中的CGBitmapContext
。