| 
                         新建自定义视图  DustEffectView,这个视图的作用是用来接收图片并将其进行沙化消失。首先创建函数createDustImages,它将一张图片的像素随机分配到32张等待动画的图片上: 
- 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 in 0..            for row in 0..                let offset = row * width + column 
 -                 //3 
 -                 for _ in 0...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 
 -     } 
 - } 
 
  
    - //1: 根据指定格式创建位图上下文,然后将输入的图片绘制上去之后获取其像素数据
 
    - //2:  创建像素二维数组,遍历输入图片每个像素,将其随机分配到数组32个元素之一的相同位置。随机方法有点特别,原始图片左边的像素只会分配到前几张图片,而原始图片右边的像素只会分配到后几张。
 
 
  
图4 上部分为原始图片,下部分为像素分配后的32张图片依次显示效果
    - //3: 这里循环2次将像素分配两次,可能 Google 觉得只分配一遍会造成像素比较稀疏。个人认为在移动端,只要一遍就好了。
 
    - //4: 创建32张图片并返回
 
 
添加动画 
                                                (编辑:滁州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |