gpt4 book ai didi

iphone - 如何同时执行两个 UI 更新?

转载 作者:可可西里 更新时间:2023-11-01 03:59:47 24 4
gpt4 key购买 nike

据我阅读 Apple 的文档得知,UI 更新只能在主线程上运行。

我的应用在屏幕的上半部分做了一些渲染,在下半部分有一个表格 View 。如果用户滚动表格而上半部分自行重新绘制,则表格会锁定半秒左右。有什么办法可以改善这种情况吗?

最佳答案

如果绘制 View 需要花费大量时间,我建议在更新时将其绘制到后台线程中的图像中,并让 View 简单地绘制图像。这将防止主线程阻塞太久。

以下代码显示了如何从后台线程创建位图上下文并将其绘制到位图上下文中。当您调用 updateInBackground 方法时,它将创建一个新的后台线程,该线程创建并绘制到上下文中,然后使用该上下文创建图像。如果将其放入 UIImageView 的自定义子类中,则图像将自动绘制到屏幕上。

- (void)updateInBackground {
[self performSelectorInBackground:@selector(_drawInBackground:) withObject:[NSValue valueWithCGRect:self.bounds]];
}
- (void)_drawInBackground:(NSValue *)boundsValue {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
CGRect bounds = [boundsValue CGRectValue];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
if(!colorSpace) {
[pool drain];
return;
}
CGContextRef context = CGBitmapContextCreate(NULL,bounds.size.width, bounds.size.height, 8, bounds.size.width * 32, colorSpace, kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
if(!context) {
[pool drain];
return;
}
CGContextConcatCTM(context, CGAffineTransformMake(1,0,0,-1,0,bounds.size.height));

// do drawing here

CGImageRef image = CGBitmapContextCreateImage(context);
[self performSelectorOnMainThread:@selector(setImage:) withObject:[UIImage imageWithCGImage:image] waitUntilDone:YES];
CGImageRelease(image);
CGContextRelease(context);
[pool drain];
}

在后台线程中绘制时,您不能使用 UIKit 对象和方法。所有绘图必须使用 Quartz functions 完成.如果你需要使用 UIKit,后台线程可以在主线程上调用一个方法来完成这部分绘图:

[self performSelectorOnMainThread:@selector(drawInMainThread:) withObject:[NSValue valueWithPointer:context] waitUntilDone:YES];

- (void)drawInMainThread:(NSValue *)value {
UIGraphicsPushContext((CGContextRef)[value pointerValue]);
// do drawing using UIKit
UIGraphicsPopContext();
}

关于iphone - 如何同时执行两个 UI 更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6903396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com