お絵かきiPhoneアプリを作ってみた #4「データ保存機能」

2015年3月18日

Objective-C xcode プログラミング 特集

お絵かきアプリも3回目になりましたが、まだ、アプリとしては使えるレベルではありません。 何故なら、アプリを終了して、再び立ち上げた時に、前回描いたモノが、消えて真っ白に戻ってしまうからですね。 今回は、保存ボタンを設置して、描いているデータを画像として保存し、アプリを再起動した時に、前回描いていた状態を復活させたいと思います。

ケース

・保存ボタンの設置 ・保存ボタンを押した時に、画面内の描画状態を画像として保存(png*透明) ・アプリ起動時に、保存されている画像があれば、その画像を描画ビューに表示させる。(引き続きドローできるようにする)

ソース

1.保存ボタンの設置

ViewController.m / -(void)makeButton //保存ボタン作成 UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //フラグ btn3.tag = 0; //[設定]サイズ、座標 btn3.frame = CGRectMake(w*2+4*2,y,w,h); //[設定]表示文字 [btn3 setTitle:@"保存" forState:UIControlStateNormal]; //[設定]文字色 [btn3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [btn3 setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal]; //[設定]透明度 btn3.alpha = 0.5; //[設定]背景色 btn3.layer.backgroundColor = [[UIColor blackColor] CGColor]; //ボタンを押した時の関数指定 [btn3 addTarget:self action:@selector(clickBtn3:) forControlEvents:UIControlEventTouchUpInside]; //画面に追加 [self.view addSubview:btn3];

2.保存ボタンを押した時のアクション

//保存ボタンを押した時の処理 -(void)clickBtn3:(id)sender{ //Documentのパス NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; //保存ファイル名 NSString *fileName = @"image1.png"; // PNGの場合(view.alphaで指定した透明度も維持されるみたい) NSData *dataSaveImage = UIImagePNGRepresentation(canvas.image); // Documentsディレクトリに保存 [dataSaveImage writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES]; NSLog(@"Image saved. %@",path); }

実行

前回までのソースコードに、上記のソースを加えて実行すると「保存」ボタンが現れて、ボタンを押すと、データが保存されるようになる。 ちなみに、現在は画像を保存するだけで、確認するには、Finderでその場所まで見に行くことで確認できる。 ファイル名は「image1.png」として保存される。 場所が少し分かりにくいのだが、NSLogで保存場所を出力しているので、見て欲しい

現時点でのソースコード

「ViewController.m」 #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //初期設定 touchMode = 0;//drawモードで開始する //キャンバス用のUIImageViewを作成 canvas = [[UIImageView alloc]init]; canvas.frame = self.view.bounds; canvas.image = [self getImageNew]; canvas.layer.borderWidth = 4; canvas.layer.borderColor = [[UIColor redColor]CGColor]; [self.view addSubview:canvas]; //機能ボタンの設置 [self makeButton]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //空白画像の作成 -(UIImage *)getImageNew{ UIImage *img = [[UIImage alloc]init]; UIGraphicsBeginImageContext(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)); img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; } /** * Touchイベント操作 */ //Touch開始処理 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ //対象のキャンバスを選択 UITouch *touch = [touches anyObject]; canvasTouch = [touch locationInView:canvas]; } //Touch動作 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ //描画処理 [self touch2draw:touches mode:touchMode]; } //Touch終了 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ } //Touchキャンセル - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ //NSLog(@"touchCancel"); } /** * 描画処理 */ /** * 描き込み * param @ touches / system-query * param @ mode / [ 0:draw 1:erase ] */ -(void)touch2draw:(NSSet *)touches mode:(int)mode{ //初期設定 float scale = 1.0f; float penSize = 20.0f; // 現在のタッチ座標をローカル変数currentPointに保持 UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:canvas]; // 描画領域をcanvasの大きさで生成 UIGraphicsBeginImageContext(canvas.image.size); //キャンバス座標 float x = 0; float y = 0; float w = canvas.image.size.width; float h = canvas.image.size.height; // canvasにセットされている画像(UIImage)を描画 [canvas.image drawInRect:CGRectMake(x,y,w,h)]; // 線の角を丸くする CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); // 線の太さを指定 CGContextSetLineWidth(UIGraphicsGetCurrentContext(), penSize); // 線の色を指定(RGB) if(mode == 1){ CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 0.0); CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeCopy); } else{ CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0); } // 線の描画開始座標をセット CGContextMoveToPoint(UIGraphicsGetCurrentContext(), canvasTouch.x*scale, canvasTouch.y*scale); // 線の描画終了座標をセット CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x*scale, currentPoint.y*scale); // 描画の開始~終了座標まで線を引く CGContextStrokePath(UIGraphicsGetCurrentContext()); // 描画領域を画像(UIImage)としてcanvasにセット canvas.image = UIGraphicsGetImageFromCurrentImageContext(); // 描画領域のクリア UIGraphicsEndImageContext(); // 現在のタッチ座標を次の開始座標にセット canvasTouch = currentPoint; } //機能ボタンの設置 -(void)makeButton{ //設置基準座標 float y = 20.0f; float w = 50.0f; float h = 30.0f; //ボタン作成 UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //フラグ btn1.tag = 1; //[設定]サイズ、座標 btn1.frame = CGRectMake(0,y,w,h); //[設定]表示文字 [btn1 setTitle:@"描く" forState:UIControlStateNormal]; //[設定]文字色 [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [btn1 setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal]; //[設定]透明度 btn1.alpha = 0.5; //[設定]背景色 btn1.layer.backgroundColor = [[UIColor blackColor] CGColor]; //ボタンを押した時の関数指定 [btn1 addTarget:self action:@selector(clickBtn1:) forControlEvents:UIControlEventTouchUpInside]; //画面に追加 [self.view addSubview:btn1]; //ボタン作成 UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //フラグ btn2.tag = 0; //[設定]サイズ、座標 btn2.frame = CGRectMake(w+4,y,w,h); //[設定]表示文字 [btn2 setTitle:@"消す" forState:UIControlStateNormal]; //[設定]文字色 [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [btn2 setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal]; //[設定]透明度 btn2.alpha = 0.5; //[設定]背景色 btn2.layer.backgroundColor = [[UIColor blackColor] CGColor]; //ボタンを押した時の関数指定 [btn2 addTarget:self action:@selector(clickBtn2:) forControlEvents:UIControlEventTouchUpInside]; //画面に追加 [self.view addSubview:btn2]; //保存ボタン作成 UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //フラグ btn3.tag = 0; //[設定]サイズ、座標 btn3.frame = CGRectMake(w*2+4*2,y,w,h); //[設定]表示文字 [btn3 setTitle:@"保存" forState:UIControlStateNormal]; //[設定]文字色 [btn3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [btn3 setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal]; //[設定]透明度 btn3.alpha = 0.5; //[設定]背景色 btn3.layer.backgroundColor = [[UIColor blackColor] CGColor]; //ボタンを押した時の関数指定 [btn3 addTarget:self action:@selector(clickBtn3:) forControlEvents:UIControlEventTouchUpInside]; //画面に追加 [self.view addSubview:btn3]; } //描くボタンを押した時の処理 -(void)clickBtn1:(id)sender{ touchMode = 0; } //消すボタンを押した時の処理 -(void)clickBtn2:(id)sender{ touchMode = 1; } //保存ボタンを押した時の処理 -(void)clickBtn3:(id)sender{ //Documentのパス NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; //保存ファイル名 NSString *fileName = @"image1.png"; // PNGの場合(view.alphaで指定した透明度も維持されるみたい) NSData *dataSaveImage = UIImagePNGRepresentation(canvas.image); // Documentsディレクトリに保存 [dataSaveImage writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES]; NSLog(@"Image saved. %@",path); } @end

今後の予定

今回は画像の保存だけだったのだが、次回は、保存した画像を、初回起動時に表示することで、再起動時に作業継続できるようにしたい。

このブログを検索

ごあいさつ

このWebサイトは、独自思考で我が道を行くユゲタの少し尖った思考のTechブログです。 毎日興味がどんどん切り替わるので、テーマはマルチになっています。 もしかしたらアイデアに困っている人の助けになるかもしれません。