我正在我的应用程序中实现“scratch”功能。用户抓取屏幕并看到“下面”的图像。
在 TouchMoved 上:我更新蒙版图像并将其应用到图层。一般来说代码是这样的:
- (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的问题...
我将不胜感激任何建议。
最佳答案
我建议你尝试其他方法,抱歉,touchesMoved功能在IOS7中运行缓慢,你的代码没有问题
关于ios - RenderInContext 在 iOS7 上非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19630088/