在我的应用程序中,用户从 UIImage 开始。根据用户输入,应用程序围绕图像的特定部分创建剪切路径。然后,我希望能够将该剪辑版本保存到应用程序的 Documents 目录中,以便以后显示。
据我所知,除了稍后显示剪辑的图像外,所有这些都进行得很顺利。一旦我尝试显示图像(通过添加自定义视图),我就会收到各种invalid context
错误,以及message sent to deallocated instance
. 虽然我不确定是什么导致了最后一个问题,但这是invalid context
我最关心的问题,因为图形上下文的概念对我来说一点也不熟悉。
以下是确切的错误:
<Error>: CGBitmapContextSetData: invalid context 0x4b997b0
<Error>: CGContextGetBaseCTM: invalid context 0x4b997b0
<Error>: CGContextConcatCTM: invalid context 0x4b997b0
<Error>: CGContextSetBaseCTM: invalid context 0x4b997b0
<Error>: CGContextSetFillColorSpace: invalid context 0x4b997b0
<Error>: CGContextSetStrokeColorSpace: invalid context 0x4b997b0
*** -[Not A Type retain]: message sent to deallocated instance 0x4b997b0
在这一点上,我将发布创建剪切路径的代码,然后是尝试将剪切图像的上下文保存为新图像的代码,最后是尝试再次显示图像的代码。正如我上面所说,在我尝试再次显示图像之前,我不会收到错误消息。
创建剪切路径:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
//Create clippingPath
UIBezierPath *edgePath = [[UIBezierPath alloc] init];
NSValue *firstPt = [edgePts objectAtIndex:0];
[edgePath moveToPoint:CGPointMake([firstPt CGPointValue].x / scaleRatio, [firstPt CGPointValue].y / scaleRatio + 20)];
[edgePts removeObject:firstPt];
for (NSValue *pt in edgePts) {
[edgePath addLineToPoint:CGPointMake([pt CGPointValue].x / scaleRatio, [pt CGPointValue].y / scaleRatio + 20)];
}
clippingPath = edgePath;
[clippingPath addClip];
[img drawAtPoint:CGPointMake(0, 20)];
clippedContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(clippedContext);
CGContextRestoreGState(ctx);
}
几乎我在上面的上下文和 contextRefs 上所做的一切对我来说都是魔法。这是我从 SO 的其他帖子拼凑而成的,基本上不知道它在做什么。令人震惊的是,我最终遇到了所有这些上下文错误,对吧?;)
保存图像,然后尝试立即显示(错误出现在最后一行):
- (void)saveCutout
{
CGImageRef clippedImageRef = CGBitmapContextCreateImage(imageView.clippedContext);
CGContextRelease(imageView.clippedContext);
UIImage *clippedImage = [UIImage imageWithCGImage:clippedImageRef];
CGImageRelease(clippedImageRef);
NSData *imgData = UIImagePNGRepresentation(clippedImage);
NSString *imgPath = [NSString stringWithFormat:@"%@/1.png", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[imgData writeToFile:imgPath atomically:NO];
//just testing to make sure it worked. first I hide the other two visible views
imageView.hidden = YES;
includedFrameView.hidden = YES;
UIImage *newImg = [[UIImage imageWithContentsOfFile:imgPath] retain];
ShowImage *imgView = [[ShowImage alloc] initWithFrame:CGRectMake(0, 0, 320, 480) andImage:newImg];
[self.view addSubview:imgView]; //ERRORS occur once this line runs
}
该类ShowImage
是一个简单的UIView
子类。它所做的只是用指定的 初始化UIImage
,它的drawRect:
方法如下:
- (void)drawRect:(CGRect)rect
{
[img drawAtPoint:CGPointMake(0, 20)];
}
值得注意的是,即使在上述drawRect:
方法中的单行被调用之前,错误也会发生(我尝试在该行上放置一个断点,但应用程序首先崩溃)。
我知道这是很多代码,但那是因为我什至不知道从哪里开始调试这个。除了解决我的特定问题外,我还希望得到一个更广泛地解决我对上下文的使用/误用的答案。