2010-10-27 145 views
4

我想要一個UITextView並允許用戶在其中輸入文本,然後將內容的副本觸發到石英位圖上下文中。有誰知道我可以如何執行此複製操作?我是否應該重寫drawRect方法並調用[super drawRect]和,然後將產生的上下文複製出來?如果是這樣,有沒有人有任何參考示例代碼複製從一個上下文到另一個?將一個UIView的繪製內容複製到另一個

更新:從閱讀下面答案中的鏈接,我把這些放在一起,試圖將我的UIView內容複製到位圖上下文中,但有些東西仍然不正確。我得到我的內容鏡像橫跨X軸(即顛倒)。我嘗試使用CGContextScaleCTM(),但似乎沒有效果。

我已驗證從前四行創建的UIImage是否正確地創建了一個不奇怪旋轉/翻轉的UIImage,所以有些事情我在後面的調用中會出錯。

// copy contents to bitmap context 
    UIGraphicsBeginImageContext(mTextView.bounds.size); 
    [mTextView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext();  

    [self setNeedsDisplay]; 

    // render the created image to the bitmap context 
    CGImageRef cgImage = [image CGImage]; 

    CGContextScaleCTM(mContext, 1.0, -1.0); // doesn't seem to change result 

    CGContextDrawImage(mContext, CGRectMake(
     mTextView.frame.origin.x, 
     mTextView.frame.origin.y, 
     [image size].width, [image size].height), cgImage); 

有什麼建議嗎?

回答

1

這裏是我用來獲取的UIView的一個UIImage代碼:

@implementation UIView (Sreenshot) 

    - (UIImage *)screenshot{ 
     UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale); 

     /* iOS 7 */ 
     BOOL visible = !self.hidden && self.superview; 
     CGFloat alpha = self.alpha; 
     BOOL animating = self.layer.animationKeys != nil; 
     BOOL success = YES; 
     if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]){ 
      //only works when visible 
      if (!animating && alpha == 1 && visible) { 
       success = [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO]; 
      }else{ 
       self.alpha = 1; 
       success = [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES]; 
       self.alpha = alpha; 
      } 
     } 
     if(!success){ /* iOS 6 */ 
      self.alpha = 1; 
      [self.layer renderInContext:UIGraphicsGetCurrentContext()]; 
      self.alpha = alpha; 
     } 

     UIImage* img = UIGraphicsGetImageFromCurrentImageContext(); 

     UIGraphicsEndImageContext(); 

     return img; 
    } 

@end 
0

可以在iOS的7使用和更高版本:

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates 
相關問題