class DustEffectView: UIView { private func createDustImages(image: UIImage) -> [UIImage] { var result = [UIImage]() guard let inputCGImage = image.cgImage else { return result } //1 let colorSpace = CGColorSpaceCreateDeviceRGB() let width = inputCGImage.width let height = inputCGImage.height let bytesPerPixel = 4 let bitsPerComponent = 8 let bytesPerRow = bytesPerPixel * width let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else { return result } context.draw(inputCGImage, in: CGRect(x: 0, y: 0, width: width, height: height)) guard let buffer = context.data else { return result } let pixelBuffer = buffer.bindMemory(to: UInt32.self, capacity: width * height) //2 let imagesCount = 32 var framePixels = Array(repeating: Array(repeating: UInt32(0), count: width * height), count: imagesCount) for column in0..for row in0.. let offset = row * width + column //3 for _ in0...1 { let factor = Double.random(in: 0..<1) + 2 * (Double(column)/Double(width)) let index = Int(floor(Double(imagesCount) * ( factor / 3))) framePixels[index][offset] = pixelBuffer[offset] } } } //4 for frame in framePixels { let data = UnsafeMutablePointer(mutating: frame) guard let context = CGContext(data: data, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else { continue } result.append(UIImage(cgImage: context.makeImage()!, scale: image.scale, orientation: image.imageOrientation)) } return result } }