Objective-C:Sprite Kit ゲーム画面(SKScene)をキャプチャしアルバムへ保存する
Sprite Kit で制作するゲームアプリで、ゲーム画面をキャプチャし、キャプチャした画像をアルバムに保存する方法をメモしておきます。
ゲーム画面(SKScene)をキャプチャしアルバムに保存する
-
キャプチャを実行したいシーン(MyScene.m)に、以下の captureScreen メソッドを記述します。
- (void)captureScreen { CGRect rect = self.frame; UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale); [self.view drawViewHierarchyInRect:rect afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // Store Image to Photo Album UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); }
-
あとは実行したいタイミングで captureScreen を呼び出せば PNG データでアルバムにキャプチャ画像が保存されます。このサンプルでは、画面タッチでスクリーンキャプチャし、キャプチャした画像をアルバムに保存します。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self captureScreen]; }
-
MyScene.m は以下のようになります。
- MyScene.m
-
#import "MyScene.h" @implementation MyScene -(id)initWithSize:(CGSize)size { if (self = [super initWithSize:size]) { self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.20 alpha:1.0]; SKLabelNode *myLabel = [SKLabelNode labelNodeWithFontNamed:@"HelveticaNeue-Bold"]; myLabel.text = @"Hello, World!"; myLabel.fontSize = 32; myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)); [self addChild:myLabel]; } return self; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self captureScreen]; } - (void)captureScreen { CGRect rect = self.frame; UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale); [self.view drawViewHierarchyInRect:rect afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // Store Image to Photo Album UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); } @end
まとめ
次回はキャプチャした画像を twitter で共有する方法を説明したいと思います。
この記事がみなさんのお役に立ちましたら、下記「Share it」よりブックマークやSNSで共有していただければ幸いです。