我有一个 IOS 应用程序,需要更新视图以响应用户或外部事件。绘制时间可以很短也可以很长(几秒),具体取决于视图中的内容。
现在,绘图是在视图的 drawRect 方法中进行的。当绘图很长且存在大量用户交互时,应用程序将变得无响应。
当需要更新时,整个视图都需要更新。如果在绘图过程中发生更改,则重新启动绘图以考虑更改是有意义的。
我想在背景中画画。
我的问题是,在 IOS 中执行此操作的最佳机制是什么?
线程,NSOperation?
我该如何处理绘图?例如,如何在线程中获取我正在更新的视图的图形上下文?
绘图操作应该如何开始?现在我正在做setNeedsDisplay。我可以改变去做别的事情。
相关视图位于 UIScrollView 内,但没有其他用户交互。
这是一个可以开始的框架。该代码假设输出视图是 UIImageView。后台任务使用位图内存上下文为输出视图创建新图像。当后台绘制任务完成时,主线程将生成的图像分配给 UIImageView。
序列号用于在完成绘制之前丢弃过时的图像。一个可能的问题是事件来得太快以至于every图像在完成之前就已经过时了。解决这个问题留给读者作为练习。
@interface SomeClass()
@property (weak, nonatomic) IBOutlet UIImageView *someView;
@property (nonatomic) int64_t sequenceNumber;
@end
@implementation SomeClass
- (UIImage *)createImageUsingBitmapMemoryContextOfSize:(CGSize)size
{
// create the memory bitmap context
UIGraphicsBeginImageContext( size );
CGContextRef context = UIGraphicsGetCurrentContext();
// draw something
[[UIColor blueColor] set];
CGContextFillEllipseInRect( context, CGRectMake(0, 0, size.width, size.height) );
// create a UIImage
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// return the image
return( result );
}
// Note: the following function should only be called on the main thread
- (void)updateInResponseToSomeEvent
{
self.sequenceNumber++;
int64_t sequenceNumber = self.sequenceNumber;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^
{
UIImage *image = [self createImageUsingBitmapMemoryContextOfSize:self.someView.bounds.size];
dispatch_async( dispatch_get_main_queue(), ^
{
if ( sequenceNumber == self.sequenceNumber )
self.someView.image = image;
});
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)