2012-05-24 2 views
0

"이미지 저장"방법을 만들고자하는 드로잉 IOS 응용 프로그램을 만듭니다. 그림이 touchesMoved : 메서드 내에서 발생합니다.CGContextRef를 .PNG 파일로 저장하는 방법은 무엇입니까?

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [touches anyObject]; 
    [self drawToCache:touch]; 
    [self setNeedsDisplay]; 
} 

- (void) drawToCache:(UITouch*)touch { 
    hue += 0.005; 
    if(hue > 1.0) hue = 0.0; 
    UIColor *color = [UIColor colorWithHue:hue saturation:0.7 brightness:1.0 alpha:1.0]; 

    CGContextSetStrokeColorWithColor(cacheContext, [color CGColor]); 
    CGContextSetLineCap(cacheContext, kCGLineCapRound); 
    CGContextSetLineWidth(cacheContext, 15); 

    CGPoint lastPoint = [touch previousLocationInView:self]; 
    CGPoint newPoint = [touch locationInView:self]; 

    CGContextMoveToPoint(cacheContext, lastPoint.x, lastPoint.y); 
    CGContextAddLineToPoint(cacheContext, newPoint.x, newPoint.y); 
    CGContextStrokePath(cacheContext); 

    CGRect dirtyPoint1 = CGRectMake(lastPoint.x-10, lastPoint.y-10, 20, 20); 
    CGRect dirtyPoint2 = CGRectMake(newPoint.x-10, newPoint.y-10, 20, 20); 
    [self setNeedsDisplayInRect:CGRectUnion(dirtyPoint1, dirtyPoint2)]; 
} 

내가 그린 그림을 .PNG 파일로 저장하고 싶습니다.

해결책이 있습니까?

+0

가능한 중복 (http://stackoverflow.com/questions/2568421/how-do-i-save-what-i-have- drawn-in-a-cgcontext) – jrturton

답변

2

당신은 실제로 경로 위치를 설정해야합니다. CrimsonDiego의 코드를 확장하면 이미지가 응용 프로그램의/Documents 디렉토리에 저장됩니다.

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *path = [docsDirectory stringByAppendingPathComponent:@"myImage.png"]; 

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image); 
[imageData writeToFile:path atomically:YES]; 
[내가이 CGContext에서 그린 것을 저장하려면 어떻게]의
+0

"[imageData writeToFile : path];"줄에 오류가 있습니다. 오류 : 'NSData'에 대해 표시되는 @interface가 선택기 'writeToFile :'을 선언합니다. – abg

+0

내 대답을 올바른 사용 방법 writeToFile로 수정했습니다. 원자 적으로 : – skram

+0

이 대답이 도움이된다면 동의하십시오. – skram

3

solution은 매우 간단합니다 :

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image); 
[imageData writeToFile:@"myImage.png"]; 
+0

이 솔루션은 저에게 효과적이지 않았습니다. 파일이 내 응용 프로그램 폴더 (~/Library/Application Support/iPhone Simulator/5.1/Applications/CCAA9512-D2D6-4312-83D6-A4A9F74906C3/*)에 나타나지 않습니다. 이 코드를 어디에 써야할까요? – abg