【スペースハリアー】UIImageをカメラロールに保存してみた
前回「【スペースハリアー】Core Graphicsでシマシマの地面を描いてみた - 夏までにiPhone アプリつくってみっか!」では画面に縞模様の地面を表示しました。
今回は、これをゲーム内のデータとして使用できるようにカメラロールに.pngファイルとしてセーブします。
前回はMyViewというUIViewのサブクラスを作ってそのdrawRect:メソッドを上書きして縞模様を表示しましたが、そうする必要がない事がわかりましたので、ViewControllerに描画処理を移しました。
プログラムはこんな感じになりました。
ViewControllerとかViewのあたりはまだ完全には理解できていないのでググった情報を集結してなんとか動く物ができました。
ファイルにUIImageの画像をセーブし終えたらそれを知らせる意味でコンプリーションハンドラーで画面に同じUIImageを表示していますが、この処理はなくてもセーブはされています。いつ終わったのかがわからないのでそうしているだけです。
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; int bandWidth = 48; int bandCount = 1000; CGFloat rectWidth = 640; CGFloat rectHeight = 320; self.view.bounds = CGRectMake(0, 0, rectWidth, rectHeight); CGFloat screenWidth = self.view.bounds.size.width; CGFloat screenHeight = self.view.bounds.size.height; CGFloat centerOffset = screenWidth/2.0; CGPoint topCenter = CGPointMake(screenWidth/2.0, 0); CGPoint startPoint = topCenter; UIColor* dark = [UIColor colorWithRed:108/255.0 green:186/255.0 blue:113/255.0 alpha:1]; UIColor* light = [UIColor colorWithRed:160/255.0 green:234/255.0 blue:162/255.0 alpha:1]; UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0); CGContextRef context = UIGraphicsGetCurrentContext(); UIColor* currentColor = dark; for (int i = -bandCount; i < bandCount; i++) { currentColor = (currentColor == dark) ? light : dark; for (int j = 0; j < bandWidth * 2; j++) { CGPoint endPoint = CGPointMake(i * bandWidth + j/2.0 + centerOffset, screenHeight); draw1PxStroke(context, startPoint, endPoint, currentColor.CGColor); } } NSData *data = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext()); UIImage *image = [UIImage imageWithData:data]; UIGraphicsEndImageContext(); UIImageWriteToSavedPhotosAlbum(image, self, @selector(finishedSavingImage:withError:contextInfo:), nil); } - (void)finishedSavingImage:(UIImage *)image withError:(NSError *)error contextInfo:(void *)contextInfo { if (!error) { UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [self.view addSubview:imageView]; } } void draw1PxStroke(CGContextRef context, CGPoint startPoint, CGPoint endPoint, CGColorRef color) { CGContextSaveGState(context); CGContextSetLineCap(context, kCGLineCapSquare); CGContextSetStrokeColorWithColor(context, color); CGContextSetLineWidth(context, 1.0); CGContextMoveToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5); CGContextAddLineToPoint(context, endPoint.x + 0.5, endPoint.y + 0.5); CGContextStrokePath(context); CGContextRestoreGState(context); }
セーブが完了するとこんな感じに画像の一部が表示されます。iPhone4Sだと約14分かかりました。
カメラロールにセーブされたファイルはこうなりました。幅1280 x 高さ640ピクセルの画像ファイルです。
https://itunes.apple.com/jp/app/travelshooting-jp-toraberushutingu/id917570972?mt=8&uo=4&at=10laCt
https://itunes.apple.com/jp/app/beecluster-wu-liaono-zongsukurorushutingugemu/id663801586?mt=8&uo=4&at=10laCt