我可以从现有的 UIImageView
获取上下文 (CGContextRef
) 吗?
详细信息:我有一个指向 xib 文件的 Controller 链接。在 IB 中,我添加了一个 UIImageView
并引用它:
IBOutlet UIImageView *imageView;
现在,在viewDidLoad
中如何获取UIImageView
上下文(CGContextRef
)?
在此之前,如果我使用:
CGContextRef context = UIGraphicsGetCurrentContext();
输出:
<Error>: CGContextTranslateCTM: invalid context
建议?
最佳答案
如果您想使用自己的绘图方法,您应该将它们应用到 UIView 的 drawRect: 方法中。您需要子类化 UIView 来创建您自己的绘图逻辑:在 XCode 中,使用 File->New File 并选择 UIView 作为模板,这将为您提供基本框架。在 Interface-Builder 中,您可以首先添加一个新 View ,然后使用 Inspector 窗口中 Identity 选项卡下的类对其进行设置。
该方法应该以类似这样的方式开始,为您提供对上下文的引用:
- (void)drawRect:(CGRect)fr {
CGContextRef context = UIGraphicsGetCurrentContext();
... DRAWING CODE ...
}
首次显示 View 时会自动调用此方法。如果您的逻辑依赖于某些变量,您应该在 UIView 上调用 setNeedsDisplay
让 View 重新运行绘图逻辑。
但是,这不适用于 UIImageView
( LINK ):
Subclassing Notes
Special Considerations
The UIImageView class is optimized to draw its images to the display. UIImageView will not call drawRect: a subclass. If your subclass needs custom drawing code, it is recommended you use UIView as the base class.
关于iphone - 从 UIImageView 获取上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1745710/