2012-10-07 18 views
0

我希望標題有一定意義。使用子視圖創建新視圖,獲取圖形上下文破壞原始視圖?

我有UIView(在IB創建),我添加的東西(圖像)。然後,我有一個帶有文本的UILabel。現在,我想打一個UIImage了這一點,我這樣做:

UIView *comp = [[UIView alloc] initWithFrame:self.previewView.frame]; 
    [comp addSubview:self.previewView]; 
    [comp addSubview:self.lblCaption]; 

    UIGraphicsBeginImageContextWithOptions(comp.bounds.size, NO, 1.0); 
    [comp.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

self.previewView和self.lblCaption都在IB創建。 previewView只是一個屏幕填充視圖。

代碼塊在按鈕點擊後在IBAction中執行。

這很棒,我得到了預期的圖像,並且可以進一步處理它。

但之後,«self.previewView»的內容不見了?當我做一個NSLog時,一切似乎都在那裏,但它在屏幕上不再可見。

有沒有人有一個想法這裏發生了什麼?

[編輯]

如以下狀態的答案,加入視圖前,self.view,所以它,當我將其添加到樣稿除去。該解決方案是很容易的,其實,我改變了代碼如下:(創建返回一個UIImage的功能,這比在代碼中做清潔了一下....

-(UIImage *)imageFromView:(UIView *)theView andLabel:(UILabel *)theLabel{ 

    UIGraphicsBeginImageContextWithOptions(comp.bounds.size, NO, 1.0); 
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    [theLabel.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return viewImage; 
} 

回答

1

我只是猜測假設可能的情況......

假設你展示self.previewView一些其他的看法,說self.view

當您添加self.previewViewcomp,它可能已經從self.view刪除。(考慮到UIView.superview只有單例如,我在想這個很可能)。

如果是這樣,在獲得圖像後重新添加self.previewViewself.view將解決問題。

+0

就是這樣,確切地說。這是邏輯,因爲self.previewView只存在一次。所以現在我在我的文章中添加了解決方案。 再次感謝 – Swissdude