RenderInContext在iOS7上非常慢



我正在我的应用程序中实现"暂存"功能。 用户刮擦屏幕并看到"下面"的图像。

在触摸移动:我更新蒙版图像并将其应用于图层。一般代码是这样的:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint cPoint = [touch locationInView:self];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];
    imageView.image = _maskImage;
    // ... add some subviews to imageView corresponding to touch manner
    _maskImage = [UIImage imageFromLayer:imageView.layer];
    [self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
    _maskImageView.image = _maskImage;
    _viewWithOurImage.layer.mask = _maskImageView.layer;
}

我使用代码从CALayer获得UIImage(UIImage上的类别):

+ (UIImage*)imageFromLayer:(CALayer*)layer
{
    UIGraphicsBeginImageContextWithOptions([layer frame].size, NO, 0);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}

这段代码在iOS6上完美运行(在iPhone 4s和iPad2上测试),完全没有延迟。

但是当我在iOS7(xcode4或xcode5)上运行它时,它非常慢和滞后。我使用了一个时间分析器,它清楚地指向渲染InContext:row。

然后我尝试了以下代码:

...
    if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
        _maskImage = [UIImage imageFromLayer:imageView.layer];
    else
        _maskImage = [UIImage imageFromViewIniOS7:imageView];
...
+ (UIImage*)imageFromViewIniOS7:(UIView*)view
{
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0);
    CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationNone);
    // actually there is NSInvocation, but I've shortened for example
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}

而且它仍然很慢。在iPhone 4s(与iOS6相同),新的iPod5和iPad3上进行了测试。

我做错了什么?显然这是iOS7的问题...

我将不胜感激任何建议。

我会建议你尝试其他方式,很抱歉,touchesMoved函数在IOS7中运行缓慢,你的代码没有错

最新更新