我错过了什么?卡了几个小时,drawRect 按预期绘制,getTheImage(( 从 viewcontoller UI 调用 UIGraphicsGetImageFromCurrentImageContext(( 返回 nil;尝试了许多变化。任何帮助,不胜感激。
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsBeginImageContext(self.bounds.size);
CGContextSetLineWidth(context, 5.0);
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor]CGColor]);
CGContextMoveToPoint(context,100.0,100.0);
CGContextAddLineToPoint(context,200.0,200.0);
CGContextMoveToPoint(context,200.0,200.0);
CGContextAddLineToPoint(context,200.0,400.0);
CGContextStrokePath(context);
}
-(UIImage *)getTheImage
{
UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
NSLog(@"drawImage %@",drawImage);
return drawImage;
}
仅当基于位图的图形上下文是当前图形上下文时,才应调用此函数。如果当前上下文为 nil 或不是通过调用 UIGraphicsBeginImageContext 创建的,则此函数返回 nil。
看起来您的呼叫不在上下文中。
你能试试这个吗?
-(UIImage *)getTheImage
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(@"drawImage %@",drawImage);
return drawImage;
}