swift - UIImage 到 UIColor 像素颜色数组

标签 swift uiimage uicolor

很抱歉问这个问题,但我不知道如何将 UIImage 表示为每个像素的 UIColor 数组。我已尽力转换 UIImagePNG/JPEGRepresentation 但无法获得所需的结果。

最佳答案

这是一个 Swiftier 版本(Swift 3):

extension UIImage {
    var colors: [UIColor]? {

        var colors = [UIColor]()

        let colorSpace = CGColorSpaceCreateDeviceRGB()

        guard let cgImage = cgImage else {
            return nil
        }

        let width = Int(size.width)
        let height = Int(size.height)

        var rawData = [UInt8](repeating: 0, count: width * height * 4)
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let bytesPerComponent = 8

        let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue

        let context = CGContext(data: &rawData,
                                width: width,
                                height: height,
                                bitsPerComponent: bytesPerComponent,
                                bytesPerRow: bytesPerRow,
                                space: colorSpace,
                                bitmapInfo: bitmapInfo)

        let drawingRect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
        context?.draw(cgImage, in: drawingRect)

        for x in 0..<width {
            for y in 0..<height {
                let byteIndex = (bytesPerRow * x) + y * bytesPerPixel

                let red = CGFloat(rawData[byteIndex]) / 255.0
                let green = CGFloat(rawData[byteIndex + 1]) / 255.0
                let blue = CGFloat(rawData[byteIndex + 2]) / 255.0
                let alpha = CGFloat(rawData[byteIndex + 3]) / 255.0

                let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
                colors.append(color)
            }
        }

        return colors
    }
}

关于swift - UIImage 到 UIColor 像素颜色数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163523/

相关文章:

ios - CGImageSourceCreateWithData 继续生成错误

ios - Swift 1.1 的新错误

ios - 为什么我的 html 没有加载到我的 WKWebView

ios - 如何在 Objective C 中像 Marquee Tag 一样为 UIImage 设置动画

ios - 公共(public)与内部访问修饰符

ios - 单击按钮时向图像添加阴影 - iOS Swift

ios - 在 iOS Objective-C 中像瓷砖一样显示图像

swift - Xcode 9 : Using named colors with IBDesignable and IBInspectable results in Interface Builder error, 但编译没有问题

ios - Swift - 设置随机 UIColor 不起作用

ios - 在 Tableview 单元格中动态应用渐变颜色 Swift