【发布时间】: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