无法获取非方形图像的字节

Can't get bytes for a non-square image

我使用this post中介绍的方法,为Swift修改:

func getRaster() -> [UIColor] {
    let result = NSMutableArray()
    
    let img = self.CGImage
    let width = CGImageGetWidth(img)
    let height = CGImageGetHeight(img)
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    
    var rawData = [UInt8](count: width * height * 4, repeatedValue: 0)
    let bytesPerPixel = 4
    let bytesPerRow = bytesPerPixel * width
    let bytesPerComponent = 8
    
    let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue
    let context = CGBitmapContextCreate(&rawData, width, height, bytesPerComponent, bytesPerRow, colorSpace, bitmapInfo)
    
    CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), img);
    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)
            result.addObject(color)
        }
    }
    
    return (result as NSArray) as! [UIColor]
}

但问题是,只有当图像是正方形(即 32x32 精灵)时它才会成功,每当我尝试获取图像的“光栅”时,其尺寸不相等,我得到一个“Index out在 x = 16 和 y = 0 上 red 的范围”致命错误(对于大小为 h:16,w:32 的图像)。什么可以解决这个问题?

提前致谢!

很容易解决,实际上,这是问题部分:

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

它应该是这样的:

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

我认为这不需要任何进一步的解释。