2012-10-17 83 views
1

我有一個圖像加載到UIImageView,其中有一個UIView覆蓋(其中繪製一個CGRect),我正在尋找一種方法來保存顯示的內容在屏幕上作爲新的圖像。我正在使用故事板和ARC。保存UIImageView和覆蓋UIView作爲圖像(xcode/iOS)

我有一個UIViewController,其中包含UIImageView。 UIView顯示在此頂部,並在用戶觸摸屏幕的位置繪製一個圓圈。這一切工作正常,但現在我想保存顯示爲圖像(JPG)。

截圖我的故事板:

enter image description here

下面是我PhotoEditViewController到目前爲止的代碼。 passedPhoto是加載到UIImageView中的照片。

#import "PhotoEditViewController.h" 
@interface PhotoEditViewController() 
@end 

@implementation PhotoEditViewController 
@synthesize selectedPhoto = _selectedPhoto; 
@synthesize backButton; 
@synthesize savePhoto; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [passedPhoto setImage:_selectedPhoto]; 
} 

- (void)viewDidUnload { 
    [self setBackButton:nil]; 
    [self setSavePhoto:nil]; 
    [super viewDidUnload]; 
} 

- (IBAction)savePhoto:(id)sender{ 
    NSLog(@"save photo"); 
    // this is where it needs to happen! 
} 

@end 

下面是我PhotoEditView代碼負責處理圓覆蓋的創建:

#import "PhotoEditView.h" 

@implementation PhotoEditView 
@synthesize myPoint = _myPoint; 

- (void)setMyPoint:(CGPoint)myPoint { 
    _myPoint = myPoint; 
    self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.01]; 
    [self setNeedsDisplay]; 
} 

- (id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    return self; 
} 

-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event { 
    NSSet *allTouches = [event allTouches]; 
    switch ([allTouches count]){ 
     case 1: { 
      UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; 
      CGPoint point = [touch locationInView:self]; 
      NSLog(@"x=%f", point.x); 
      NSLog(@"y=%f", point.y);  
      self.myPoint = point; 
     } 
     break; 
    } 
} 

- (void)drawRect:(CGRect)rect { 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(ctx, 4.0); 
    CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.5); 
    CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1); 
    CGContextStrokePath(ctx); 
    CGRect circlePoint = CGRectMake(self.myPoint.x - 50, self.myPoint.y - 50, 100.0, 100.0); 
    CGContextStrokeEllipseInRect(ctx, circlePoint); 
} 

@end 

任何幫助,將不勝感激。

回答

3

你有沒有嘗試過這樣的:

UIGraphicsBeginImageContext(rect.size); 

[imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
[customView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

UIImageView *imgView = [[UIImageView alloc] initWithImage:viewImage]; 

這只是同樣的方法爲從UIView得到一個UIImage,只有你畫在同一背景下兩種觀點。

+0

謝謝,你有更完整的代碼或完整的例子嗎? –

+0

我解決了代碼中存在的問題,但是:更完整的示例是什麼意思?我知道這是相當完整的,它會給你從你的兩個意見的圖像......或通過「保存」你的意思是保存到磁盤? – sergio

+0

很感謝,我最終以不同的方式做了,但你讓我走在正確的道路上:) –