2011-06-01 26 views
3

我有一個幻燈片,允許用戶使用簡單的繪圖工具來註釋幻燈片。只需讓您用手指在屏幕上繪製,然後「保存」即可。保存功能使用UIImagePNGRepresentation,工作得很好。我需要解決的是如何「繼續」現有註釋,以便在發生保存時也考慮幻燈片中已有的內容。將圖像添加到當前UIGraphics上下文

它使用UIImageContext並將該圖像上下文保存到文件中。當一個圖像被保存時,它會打開一個疊加的UIImageView,所以如果你正在'繼續',那麼你將繪製到一個現有的png文件上。

有沒有一種方法可以將現有圖像添加到UIImageContext?在這裏,我在控制運動添加行:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    if(drawToggle){ 
     UITouch *touch = [touches anyObject]; 
     CGPoint currentPoint = [touch locationInView:self.view]; 
     currentPoint.y -= 40; 

     //Define Properties 
     [drawView.image drawInRect:CGRectMake(0, 0, drawView.frame.size.width, drawView.frame.size.height)]; 
     CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
     CGContextSetLineJoin(UIGraphicsGetCurrentContext(), kCGLineJoinBevel); 
     CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0); 
     CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0); 
     //Start Path 
     CGContextBeginPath(UIGraphicsGetCurrentContext()); 
     CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); 
     CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y); 
     CGContextStrokePath(UIGraphicsGetCurrentContext()); 
     //Save Path to Image 
     drawView.image = UIGraphicsGetImageFromCurrentImageContext(); 

     lastPoint = currentPoint; 
    } 
} 

這裏是神奇的節約行:

NSData *saveDrawData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext()); 
NSError *error = nil; 
[saveDrawData writeToFile:dataFilePath options:NSDataWritingAtomic error:&error]; 

感謝您可以提供任何幫助。

UPDATE:

哎呀我忘了補充,當一個註釋「拯救」圖像內容結束了,所以我不能使用任何獲取當前圖像內容風格的方法。

回答

9

我通過我的起始和終止行之間添加此實現這一點:

UIImage *image = [[UIImage alloc] initWithContentsOfFile:saveFilePath]; 
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);  
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, image.size.height); 
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0); 
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage); 

語境翻譯和檯秤是必要的,因爲一個UIImage轉換爲CGImage翻轉圖像 - 它這樣做是因爲一個CGImage從平一個左下角的原點和UIImage從左上角的原點繪製,相同的座標以翻轉的比例導致翻轉的圖像。

因爲我在保存文件時將現有圖像繪製到UIGraphicsGetCurrentContext()中,因此將其考慮在內。