2017-08-19 42 views
-1

我想捕獲圖像中的當前屏幕。我這樣做:UIGraphicsBeginImageContext不返回視網膜圖像

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.isOpaque, UIScreen.main.scale) 
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: false) 
let snapshot = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 

問題是規模參數。如果我理解正確,0.0代表非視網膜,2.0代表視網膜,3.0代表6加和7加視網膜。無論我輸入到scale參數中,輸出始終是375x667分辨率的圖像。我也嘗試了不同的方法:

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.isOpaque, UIScreen.main.scale) 
self.view.layer.render(in: UIGraphicsGetCurrentContext()!) 
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 

同樣的情況。我甚至使用

UIScreen.main.scale

這實際上回報價值2.0。我究竟做錯了什麼?我如何獲得更高分辨率的圖像?

+0

實際上,0.0表示實際的屏幕比例,而不是非視網膜。那是1.0。 – the4kman

+0

你如何確定最終圖像的「大小」? –

+0

「分辨率」是什麼意思?唯一不同的是UIImage的「scale」。尺寸以點爲單位,而不是像素;所有的比例都是一樣的。 – matt

回答

0

此代碼將這樣的伎倆

let contextSize = CGSize(width: self.view.bounds.size.width * UIScreen.main.scale, height: self.view.bounds.size.height * UIScreen.main.scale) 

UIGraphicsBeginImageContextWithOptions(contextSize, self.view.isOpaque, UIScreen.main.scale) 
self.view.layer.render(in: UIGraphicsGetCurrentContext()!) 
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 

CGContext不關心規模,它關心的只是大小。

編輯

您可能需要使用可用的新API iOS中10及更高版本

let renderer = UIGraphicsImageRenderer(bounds: self.view.bounds) 

let snapshot = renderer.image(actions: { context in 
    self.view.layer.render(in: context.cgContext) 
}) 
+0

這只是做到了這一點:http://i.imgur.com/hKXsmkY。jpg(藍色是抓取的截圖) – MHCsk

+0

嘗試通過** 0 **作爲比例 – Karim

+0

仍然一樣。 – MHCsk

0

快照UIImage它有兩個屬性,sizescale;很像屏幕。要確定圖像像素的實際大小,您必須將大小乘以比例。我認爲你的問題是你認爲size屬性是像素而不是點。

size
圖像的邏輯尺寸,以點爲單位。

您可以通過使用UIImageJPEGRepresentation創建JPG,並將其保存到磁盤在一個非常明確的方式測試這種使用圖像工具你熟悉檢查。

0

問題是你的期望是錯誤的;你不明白什麼是解決方案。 size對於1x圖像,其相應的2x圖像及其對應的3x圖像是相同的。不同之處在於圖片的scale;如果你看一下,你會發現它是正確的。

如果你想證明這一點你自己,將UIImage轉換爲CGImage並看看的大小。現在您可以看到底層位圖的尺寸。