2017-03-18 48 views
-3

使用- (nullable UIView *)resizableSnapshotViewFromRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates withCapInsets:(UIEdgeInsets)從包含AVCaptureVideoPreviewLayer的UIView獲得快照,然後我想將結果(UIView *)轉換爲UIImage並顯示,但UIImage是空的每時每刻。無法在U盤上將UIView轉換爲UIImage 9.3.5

CGRect frame = CGRectMake(0, 0, 768, 893); 
UIView *photo = [self.cameraView resizableSnapshotViewFromRect:frame afterScreenUpdates:YES withCapInsets:UIEdgeInsetsZero]; 

UIGraphicsBeginImageContextWithOptions(photo.bounds.size, NO, [[UIScreen mainScreen] scale]); 
[photo drawViewHierarchyInRect:photo.bounds afterScreenUpdates:YES]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

UIImageView * iv = [[UIImageView alloc] initWithImage:image]; 
[iv setFrame:CGRectMake(0, 0, image.size.width, image.size.height)]; 
[self addSubview:iv]; 

CALayer * layer = [iv layer]; 
layer.borderWidth = 2.0f; 
layer.borderColor = [[UIColor orangeColor] CGColor]; 

有沒有人知道爲什麼不能得到正確的UIImage?

Xcode Version 8.2.1 (8C1002) MacOS Sierra 10.12.3(16D32) Deployment Target 9.3 iPad iOS 9.3.5

回答

-1

我不知道這樣做的Objective-C的版本,而是試圖將其轉換爲對象 - 自己,並添加以下代碼:

let context = UIGraphicsGetCurrentContext() 
photo.layer.render(in:context!) 

後添加它

[photo drawViewHierarchyInRect:photo.bounds afterScreenUpdates:YES];

但在此之前

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

+0

'[photo.layer renderInContext:UIGraphicsGetCurrentContext()]'不起作用 – leezhm

+0

@leezhm嗯..我認爲它會工作..你確定你的UIView已被繪製?你在那個draw-function中發送'afterScreenUpdates:YES',你知道這個代碼的含義嗎?我不..也許它會在繪製視圖之前等待屏幕準備就緒,但其餘代碼會立即顯示出來。嘗試將其更改爲「否」? – Sti

+0

嘗試是和否,它不起作用!我的項目是一個iPad應用程序,我發現這個話題https://github.com/jfradj/ScreenshotIssue http://stackoverflow.com/questions/25432222/drawviewhierarchyinrectafterscreenupdates-and-renderincontext-dont-work-ot – leezhm

-1

用下面的方法(未經測試):

- (UIImage *)renderViewToImage:(UIView *)view 
{ 
    UIImage* image = nil; 

    UIGraphicsBeginImageContext(view.bounds.size);   
    [view.layer renderInContext: UIGraphicsGetCurrentContext()];   
    image = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext(); 

    return image 
} 

而且撥打:

UIImage *img = [self renderViewToImage:photo] 

您可能要使它成爲一個類別來UIView

+0

測試你的代碼並沒有工作 – leezhm

+0

我現在沒有機會測試。嘗試'view.bounds.size'而不是'view.frame.size'。讓我們知道發生了什麼「不起作用」。 – shallowThought

+0

沒有工作!我的項目是一個iPad應用程序,我發現這個https://github.com/jfradj/ScreenshotIssue – leezhm