从图像文件创建 CIImage 模式

Create CIImage Pattern from image file

我正在尝试了解什么是最高效创建CIImage带有基于图像文件的模式的方法。

let patternImage = UIImage(named: "pattern.png")

我采用的第一种方法:

// First create UIColor pattern
let uiColorPattern = UIColor(patternImage: patternImage!) 

// Than init CIColor using the UIColor pattern object
let ciColorPattern = CIColor(color: uiColorPattern)

// Finally, create CIImage using the CIColor initialiser
let ciImagePattern = CIImage(color: ciColorPattern) //

遗憾的是,由于未知原因,CIImage 只是空白。我也试过应用 clampedToExtent() 而不是裁剪它,但它仍然是空白的。

我采用的第二种方法(有效但太慢):

UIGraphicsBeginImageContext(size) // create context

patternImage?.drawAsPattern(in: rect) // draw pattern as 'UIImage'

let patternUIImage = UIGraphicsGetImageFromCurrentImageContext() // fetch 'UIImage'

UIGraphicsEndImageContext() // end context

if let patternUIImage = patternUIImage {
     let ciImagePattern = CIImage(image: patternUIImage) // Create 'CIImage' using 'UIImage'
}    

此方法有效,但正如我所说,太慢了。


总的来说,我的直觉是,如果我能让第一种方法起作用,它将比第二种方法更有效。

任何其他 approaches/suggestions 将不胜感激!

您采用的第一种方法无效 来自 WWDC 2013:

So, because, you know, and CIColor doesn't handle color spaces, it won't do CMYK color, it won't do patterns.

So, these are all things that you're going to lose.

If you ever think that you're going to need that, then probably not the right strategy.

所以第二种方法是我们可以优化的。我有一个片段,其中 returns 一个图案图像,您可以试一试。

        let myImage = UIImage.init(named: "www")
        let imageSize = myImage?.size
        let imageWidth = imageSize?.width
        let imageHeight = imageSize?.height
        let widthIterations = self.view.bounds.size.width / imageWidth!
        let heightIterations = self.view.bounds.size.height / imageHeight!

        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, true, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()


            for i in 0 ... Int(heightIterations) {
                let yPoint = CGFloat(i) * imageHeight!
                for j in 0 ... Int(widthIterations) {
                    let xPoint = CGFloat(j) * imageWidth!
                    myImage?.draw(at: CGPoint.init(x: xPoint, y: yPoint))
                }
            }
        let tempImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()