gpt4 book ai didi

ios - 使用队列时 UIGraphicsGetImageFromCurrentImageContext 崩溃

转载 作者:行者123 更新时间:2023-11-29 01:55:22 25 4
gpt4 key购买 nike

我试图了解我的代码在使用队列时崩溃的方式,但在使用主线程时却能正常工作。此代码运行良好:

- (void)penMoved:(NSSet *)touches {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
CGPoint midPoint = midpoint(previousPoint, currentPoint);

CGRect bounds = self.bounds;
UIGraphicsBeginImageContextWithOptions(bounds.size, YES, [UIScreen mainScreen].scale);

[path addQuadCurveToPoint:midPoint controlPoint:previousPoint];
[incrementalImage drawAtPoint:CGPointZero];
[path stroke];

previousPoint = currentPoint;

incrementalImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

[self setNeedsDisplay];
}

但是,当调用 incrementalImage = UIGraphicsGetImageFromCurrentImageContext(); 时,此版本的代码会在一段时间后崩溃。

- (void)penMoved:(NSSet *)touches {
dispatch_async(drawingQueue, ^{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
CGPoint midPoint = midpoint(previousPoint, currentPoint);

CGRect bounds = self.bounds;
UIGraphicsBeginImageContextWithOptions(bounds.size, YES, [UIScreen mainScreen].scale);

[path addQuadCurveToPoint:midPoint controlPoint:previousPoint];
[incrementalImage drawAtPoint:CGPointZero];
[path stroke];

previousPoint = currentPoint;

incrementalImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

dispatch_async(dispatch_get_main_queue(), ^{
[self setNeedsDisplay];
});
});
}

drawingQueue 定义为这样的 ivar:

dispatch_queue_t drawingQueue;

并像这样初始化:

drawingQueue = dispatch_queue_create("drawingQueue", NULL);

最佳答案

你说的是触摸。你在谈论一个观点。这些东西不是线程安全的。您不得在后台线程中谈论它们。您正在谈论两个不同线程上的 incrementalImage 属性。这就是明显的危险;那里也有其他属性。

关于ios - 使用队列时 UIGraphicsGetImageFromCurrentImageContext 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30925870/

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