我需要制作一個快速更新 UIImage 的功能肉迫,一開始使用 UIImageView 來顯示圖片譬巫,所以需要頻繁的調(diào)用 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
經(jīng)過我一番搜索嘗試了以下配置美澳,均無任何幫助:
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內(nèi)雨膨,保持圖片比例最大的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)
// 創(chuàng)建一個和 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 }
// 圖片直接繪制的話擂涛,會上下翻轉(zhuǎn),因此先翻轉(zhuǎn)一下
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,因為是在做一塊類似后期調(diào)照片的軟件排监,有很多滑塊狰右,拖動后通過 CIFilter 修改照片,所以需要一直更新圖像舆床,如果有更好的方法棋蚌,不妨告訴我一下:D
如果以上內(nèi)容對你有所幫助嫁佳,請在這些平臺上關注我吧,謝謝:P