【问题标题】:Creating a UIImage from a UIImageView and a UITextView从 UIImageView 和 UITextView 创建 UIImage
【发布时间】:2013-04-24 11:31:37
【问题描述】:

我正在使用上一个答案中的以下代码通过组合 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

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

【问题讨论】:

  • 我看到你做了 [parentView sizeToFit];你确定框架不是 CGRectZero 吗?
  • 那是因为 parentView 帧大小仍然为零。使用 NSLog 检查框架。

标签: ios objective-c uigraphicscontext


【解决方案1】:

sizeToFit 不适用于 UIView。您必须重写此方法才能按预期工作。见iphone uiview - resize frame to fit subviewsHaving trouble getting UIView sizeToFit to do anything meaningful

【讨论】:

  • 我已经设法改变它,以便 uiimageview 设置 UIView 的大小
【解决方案2】:

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

根据文档

UIGraphicsGetCurrentContext()

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    相关资源
    最近更新 更多