アプリケーションに「スクラッチ」機能を実装しています。ユーザーが画面を引っ掻くと、「下」の画像が表示されます。
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: 行を明確に示しています。
次に、次のコードを試しました:
...
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の問題です...
提案をいただければ幸いです。