UIGraphicsGetImageFromCurrentImageContext返回意外的nil

时间:2011-11-24 10:40:51

标签: iphone ios quartz-graphics


我有以下代码:

CGContextRef ctx = UIGraphicsGetCurrentContext();
UIGraphicsBeginImageContext(size);
screenImageContext = UIGraphicsGetCurrentContext();
ctx = screenImageContext;

UIGraphicsPushContext(UIGraphicsGetCurrentContext());
ctx  = UIGraphicsGetCurrentContext();

NSLog(@" %@",screenImageContext);
UIImage * result = UIGraphicsGetImageFromCurrentImageContext(); // Returns nil

UIImageWriteToSavedPhotosAlbum(result, nil, nil, nil);

UIGraphicsPopContext();
result = UIGraphicsGetImageFromCurrentImageContext(); // returns valid result

我的问题是UIGraphicsGetImageFromCurrentImageContext返回nil,而UIGraphicsPopContext后面的第二个返回正确的结果。

文档明确指出,当上下文为nil或当前上下文不是图形上下文时,UIGraphicsGetImageFromCurrentImageContext将返回nil,但这两个问题都不会发生在这里。

如果有人能对此有所了解,我会非常感激 晒。

1 个答案:

答案 0 :(得分:5)

根据我对事情的理解,你的问题源于以下几行

UIGraphicsPushContext(UIGraphicsGetCurrentContext());

通过此调用,您尝试将当前上下文设置为当前上下文。这真的没有任何意义。

此外,您的代码有点乱,您调用UIGraphicsGetCurrentContext()将返回当前上下文,然后调用UIGraphisBeginImageContext(CGSize size),如文档中所述

  

创建基于位图的图形上下文并使其成为当前上下文

然后你再次获得当前的图形上下文,这是一个基于位图的图形上下文,这要归功于之前的调用,然后你覆盖刚刚检索到的原始CGContextRef(“ctx”)。

我不是100%肯定你的目标是用你的代码实现的,但是如果你只是想在图像中捕获基于位图的上下文的内容并将其保存到相册,那么下面的代码将会那样做。

CGSize size = CGSizeMake(320, 480); //Screen Size on iPhone device
UIGraphicsBeginImageContext(size);  //Create a new Bitmap-based graphics context (also makes this the current context)
CGContextRef screenImageContext = UIGraphicsGetCurrentContext(); //get a reference to the context we just made above
NSLog(@" %@",screenImageContext);
//NOTE: without any drawring code in here this will just be a blank image (white/alpha)
// or an image set to whatever the current UIColor is set to
//So you may want to add some drawing code in here. Although TBH I'm not sure what you were originally
// trying to achieve.
UIImage * result = UIGraphicsGetImageFromCurrentImageContext(); // Returns nil
NSLog(@" %@",result); //just output this to demonstrate that it's non null/nil
UIImageWriteToSavedPhotosAlbum(result, nil, nil, nil);
UIGraphicsEndImageContext(); //Removes the current bitmap-based graphics context from the top of the stack

希望有所帮助。