【问题标题】:RenderInContext is incredibly slow on iOS7iOS7 上的 RenderInContext 非常慢
【发布时间】:2013-10-28 08:29:32
【问题描述】:

我正在我的应用程序中实现“临时”功能。用户划伤屏幕并看到“下方”的图像。

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

- (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)上运行它时,它非常缓慢和滞后。我使用了一个时间分析器,它清楚地指向了 renderInContext: 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的问题...

我会很感激任何建议。

【问题讨论】:

  • 你需要renderInContext吗?为什么不在你的视图上设置 layer.mask 呢?
  • @nielsbot 哇,我怎么没注意到!现在它非常快:))谢谢!
  • 仅供参考——我认为遮罩层仍然需要 CPU 渲染等,但对于您的应用程序来说似乎是不可避免的。
  • @nielsbot 在 iPod5 和 iPod4 上非常快,完全没有延迟。谢谢。

标签: ios objective-c ios7


【解决方案1】:

我建议你尝试一下其他方法,很抱歉,touchesMoved功能在IOS7中运行缓慢,你的代码没有问题

【讨论】:

  • 你说得对,我从触摸切换到平移手势识别器,现在它在 iOS6 和 iOS7 上运行良好。谢谢!但是@nielsbot 指出了我的代码中的其他愚蠢错误。所以现在复杂的一切都是完美的。谢谢大家。
猜你喜欢
  • 1970-01-01
  • 2021-02-16
  • 2020-09-21
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多