I am implementing "scratch" functionality in my application. User scratches the screen and sees the image "below".
On touchesMoved: I update mask image and apply it to layer. In general code is like this:
- (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;
}
I get UIImage from CALayer using code (category on UIImage):
+ (UIImage*)imageFromLayer:(CALayer*)layer
{
UIGraphicsBeginImageContextWithOptions([layer frame].size, NO, 0);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
This code works perfectly on iOS6 (tested on iPhone 4s and iPad2), no lags at all.
But when I run it on iOS7 (xcode4 or xcode5), it is awfully slow and laggy. I used a time profiler, it clearly points to renderInContext: row.
Then I tried following code:
...
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;
}
And it is still very slow. Tested on iPhone 4s (same as was on iOS6), new iPod5 and iPad3.
What am I doing wrong? Obviously it's a problem with iOS7...
I will appreciate any suggestions.
我会建议您尝试其他方法,抱歉地说, touchesMoved函数在IOS7中运行缓慢,您的代码没有错
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.