0

我正在使用先前答案中的以下代码通过组合 UIImageView 和 UITextView 创建新的 UIImage。

UIView *parentView = [[UIView alloc] initWithFrame:CGRectZero];
[parentView addSubview:self.imagePreview];
[self.imagePreview setFrame:CGRectMake(0, 0, 100, 100)];
[parentView addSubview:self.memeTextFieldTop];
[self.memeTextFieldTop setFrame:CGRectMake(20, 20, 80, 20)];
[parentView sizeToFit];

UIGraphicsBeginImageContext([parentView bounds].size);
[[parentView layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

问题似乎是我目前遇到以下错误,我不确定如何解决它们。

<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextSetAlpha: invalid context 0x0
<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextGetBaseCTM: invalid context 0x0
<Error>: CGContextConcatCTM: invalid context 0x0
<Error>: CGContextSetBaseCTM: invalid context 0x0
<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextSetAlpha: invalid context 0x0
<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextConcatCTM: invalid context 0x0

任何想法如何解决这个问题?

4

2 回答 2

1

日志显示您没有有效的绘图上下文

根据文档

UIGraphicsGetCurrentContext()

当前图形上下文默认为 nil。在调用它的 drawRect: 方法之前,视图对象将一个有效的上下文压入堆栈,使其成为当前的。但是,如果您不使用 UIView 对象进行绘图,则必须使用 UIGraphicsPushContext 函数手动将有效上下文推送到堆栈上。

通过使用您创建的上下文调用 UIGraphicsPushContext(),您的其他方法可以使用 UIGraphicsGetCurrentContext() 访问该上下文。

如果您在drawRect: 之外调用 UIGraphicsGetCurrentContext()并且没有使用 UIGraphicsPushContext() 显式设置上下文,则当前的图形上下文是未定义的——当然使用起来也不安全

于 2013-04-24T12:03:15.137 回答
1

sizeToFit 不适用于 UIView。您必须重写此方法才能按预期工作。请参阅iphone uiview - resize frame to fit subviews在让 UIView sizeToFit 做任何有意义的事情时遇到问题

于 2013-04-24T12:12:54.900 回答