2017-06-26 16 views
0

如果我通過CALayer的renderInContext接口使用從'UIGraphicsGetCurrentContext'獲得的上下文,我可以正確地獲取UIView的快照,但是如果使用由'CGBitmapContextCreate'創建的上下文,快照圖像將被鏡像並旋轉180度,即使兩個上下文具有相同的「寬度」,「高度」,「位圖信息」(8198,表示'kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little')和'色彩空間'(等於CGColorSpaceCreateDeviceRGB())。我可以用創建的CGContextRef調用CALayer的renderInContext嗎?

的代碼運行正常:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.bounds.size.width, view.bounds.size.height), YES, 1); 
[view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIGraphicsEndImageContext(); 

代碼得到反映和旋轉圖像:

CGContextRef context = 0; 
CGColorSpaceRef colorSpace; 
size_t width = view.bounds.size.width; 
size_t height = view.bounds.size.height; 
size_t bitsPerPixel = 32; 
size_t bitsPerComponent = 8; 
size_t bytesPerPixel = bitsPerPixel/bitsPerComponent; 
size_t bytesPerRow = width * bytesPerPixel; 
colorSpace = CGColorSpaceCreateDeviceRGB(); 
uint32_t *buffer = new uint32_t[width * height]; 
context = CGBitmapContextCreate(buffer, 
            width, 
            height, 
            bitsPerComponent, 
            bytesPerRow, 
            colorSpace, 
            kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little); 
CGColorSpaceRelease(colorSpace); 
[view.layer renderInContext:context]; 
+0

有一篇關於同樣的事情的帖子:https://stackoverflow.com/questions/7856127/using-calayers-renderincontext-method-with-geometryflipped?rq = 1答案是'翻轉目標上下文之前你渲染它「,但是爲什麼? – XiangmeiNorth

+0

上下文具有'ctm'屬性,不是嗎? – kelin

+0

我沒有設置任何圖層的geometryFlipped屬性,爲什麼我應該做這個變換? – XiangmeiNorth

回答

0

我不知道它可以幫助你或沒有。 但我試圖解決你的問題,我就這樣完成了。

{

CGContextRef context = 0; 

CGColorSpaceRef colorSpace; 
size_t width = width; 
size_t height = height; 
size_t bitsPerPixel = 32; 
size_t bitsPerComponent = 8; 
size_t bytesPerPixel = bitsPerPixel/bitsPerComponent; 
size_t bytesPerRow = width * bytesPerPixel; 
colorSpace = CGColorSpaceCreateDeviceRGB(); 
uint32_t *buffer = new uint32_t[width * height]; 
context = CGBitmapContextCreate(buffer, 
           width, 
           height, 
           bitsPerComponent, 
           bytesPerRow, 
           colorSpace, 
           kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little); 
CGColorSpaceRelease(colorSpace); 
[view.layer renderInContext:context]; 

UIImage *newImg = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)]; 

}

,如果您檢查newImg你可以看到結果。

+0

我看到了結果,結果圖像被鏡像和旋轉。 – XiangmeiNorth

+0

總之,圖像是垂直翻轉的。 – XiangmeiNorth

相關問題