我需要制作一個快速更新 UIImage 的功能,一開始使用 UIImageView 來顯示圖片,所以需要頻繁的調用 UIImageView.image = newImage
方法來更新圖片。代碼看起來像這樣。
func onSomethingChanged() {
myUIImageView.image = newImage
}
這樣更新圖片非常的卡頓,操作和畫面響應有一定的滯后,體驗不好,因此考慮自己做一個 UIView 來繪制圖片,看看是否可以解決。
于是自己自定義了一個 View,繼承 UIView 來做,在 draw(rect:)
方法里面做文章。
首先當然是簡單粗暴直接 UIImage.draw(in: bounds)
先看看效果。
var image: UIImage? {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
ctx.addRect(bounds)
ctx.setFillColor(UIColor.black.cgColor)
ctx.fillPath()
if var im = image {
im.draw(in: bounds)
}
}
很好,更新速度很快,是理想的效果,不過目前畫面是拉伸的,同時還有鋸齒。
下圖中左邊是理想的顯示效果,右邊則是實際的顯示效果,可以看到明顯的鋸齒。
image.png
經過我一番搜索嘗試了以下配置,均無任何幫助:
ctx.setShouldAntialias(true)
ctx.setAllowsAntialiasing(true)
ctx.interpolationQuality = .high
layer.allowsEdgeAntialiasing = true
layer.minificationFilter = .trilinear
我回憶起之前用 CGImageContext 縮放圖片的時候也沒有這個問題啊,難道是因為 UIView 自帶的這個 CGContext 無法很好的縮放圖片?
于是我想到一個方案:先用一個 CGImageContext 把圖片畫上去,再弄出一個 CGImage 來,再把這個 CGImage 放到 UIView 的 CGContext 上是否可以呢?
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
ctx.addRect(bounds)
ctx.setFillColor(UIColor.black.cgColor)
ctx.fillPath()
if var im = image {
// 計算出在當前view的bounds內,保持圖片比例最大的size
let size = Math.getMaxSizeWithAspect(size: CGSize(width: bounds.width, height: bounds.height), radioWidthToHeight: im.size.width / im.size.height)
// 再換算成pixel size
let pixelSize = CGSize(width: size.width * layer.contentsScale, height: size.height * layer.contentsScale)
// 創建一個和 pixel size 一樣大的 ImageContext
UIGraphicsBeginImageContextWithOptions(pixelSize, true, 1)
guard let imgCtx = UIGraphicsGetCurrentContext() else { return }
// 把 UIImage 畫到這個 ImageContext 上
im.draw(in: CGRect(x: 0, y: 0, width: pixelSize.width, height: pixelSize.height))
// 再把 cgImg 搞出來
guard let cgImg = imgCtx.makeImage() else { return }
// 圖片直接繪制的話,會上下翻轉,因此先翻轉一下
ctx.scaleBy(x: 1, y: -1)
ctx.translateBy(x: 0, y: -bounds.height)
// 再把cgImg 畫到 UIView 的 Context 上,大功告成
ctx.draw(cgImg, in: CGRect(x: (bounds.width - size.width) / 2, y: (bounds.height - size.height) / 2, width: size.width, height: size.height))
}
}
問題就此得到解決。
其實我的本身需求是能快速的更新 image,因為是在做一塊類似后期調照片的軟件,有很多滑塊,拖動后通過 CIFilter 修改照片,所以需要一直更新圖像,如果有更好的方法,不妨告訴我一下:D
如果以上內容對你有所幫助,請在這些平臺上關注我吧,謝謝:P