我希望標題有一定意義。使用子視圖創建新視圖,獲取圖形上下文破壞原始視圖?
我有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;
}
就是這樣,確切地說。這是邏輯,因爲self.previewView只存在一次。所以現在我在我的文章中添加了解決方案。 再次感謝 – Swissdude