[IOS] 自定義View繪製UIImage出現鋸齒如何解決

我須要製做一個快速更新 UIImage 的功能,一開始使用 UIImageView 來顯示圖片,因此須要頻繁的調用 UIImageView.image = newImage 方法來更新圖片。代碼看起來像這樣。git

func onSomethingChanged() {
    myUIImageView.image = newImage
}

這樣更新圖片很是的卡頓,操做和畫面響應有必定的滯後,體驗很差,所以考慮本身作一個 UIView 來繪製圖片,看看是否能夠解決。github

因而本身自定義了一個 View,繼承 UIView 來作,在 draw(rect:) 方法裏面作文章。swift

首先固然是簡單粗暴直接 UIImage.draw(in: bounds) 先看看效果。ide

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)
    }
}

很好,更新速度很快,是理想的效果,不過目前畫面是拉伸的,同時還有鋸齒。spa

下圖中左邊是理想的顯示效果,右邊則是實際的顯示效果,能夠看到明顯的鋸齒。code

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 上是否能夠呢?get

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))
    }
}

問題就此獲得解決。it

其實個人自己需求是能快速的更新 image,由於是在作一塊相似後期調照片的軟件,有不少滑塊,拖動後經過 CIFilter 修改照片,因此須要一直更新圖像,若是有更好的方法,不妨告訴我一下:D

若是以上內容對你有所幫助,請在這些平臺上關注我吧,謝謝:P

相關文章
相關標籤/搜索