IOS Quartz2D无法从当前上下文中获取图像
问题描述:
我错过了什么?被卡住了几个小时,drawRect按预期绘制,getViewImage()从viewcontoller中调用UIGraphicsGetImageFromCurrentImageContext()返回nil;尝试了很多变化。 任何帮助表示赞赏。IOS Quartz2D无法从当前上下文中获取图像
- (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;
}
答
只有当基于位图的图形上下文是当前图形上下文,您应该调用这个函数。如果当前上下文为零,或者不是通过调用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;
}
感谢您的回应,仍然无法正常工作UIGraphicsBeginImageContext仅需要1个参数。 –
已将UIGraphicsBeginImageContext更改为UIGraphicsBeginImageContextWithOptions,仍然不行 –
对UIGraphicsBeginImageContextWithOptions抱歉。你能告诉我你从哪里调用这个getTheImage方法吗?我从视图控制器的viewWillAppear和viewDidAppear方法中调用了这个方法,并且从这两个地方的图像都不是零。 但是,当我从viewDidLoad调用此方法时,图像即将变为零。 只有完全加载视图后,才应调用getTheImage方法。 –