Ios Can';无法获取非方形图像的字节

Ios Can';无法获取非方形图像的字节,ios,swift,core-graphics,Ios,Swift,Core Graphics,我使用了在中介绍的、为Swift修改的方法: func getRaster() -> [UIColor] { let result = NSMutableArray() let img = self.CGImage let width = CGImageGetWidth(img) let height = CGImageGetHeight(img) let colorSpace = CGColorSpaceCreateDeviceRGB()

我使用了在中介绍的、为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]
}
func getRaster()->[UIColor]{
让结果=NSMutableArray()
设img=self.CGImage
let width=CGImageGetWidth(img)
let height=CGImageGetHeight(img)
让colorSpace=CGColorSpaceCreateDeviceRGB()
var rawData=[UInt8](计数:宽度*高度*4,重复值:0)
设字节/像素=4
让bytesPerRow=bytesPerPixel*宽度
让bytesPerComponent=8
设bitmapInfo=CGImageAlphaInfo.PremultipledLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue
let context=CGBitmapContextCreate(&rawData、宽度、高度、bytesPerComponent、bytesPerRow、颜色空间、bitmapInfo)
CGContextDrawImage(上下文,CGRectMake(0,0,CGFloat(宽度),CGFloat(高度)),img);

对于0中的x…这很容易解决,事实上,问题在于:

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

用于0中的x。为了澄清,我已经得到了Swift版本的解释。它现在也被修复了。这将从阵列重新分配中产生大量开销。如果预先分配阵列,性能将大大提高。事实上,这确实没有理由使用
NSMutableArray
而不是本机Swift
array
@再一次,我使用了一个在中介绍的实现。我实际使用的一个有点不同,是的,我同意,这是绝对没有理由的。是的,我知道。仍然认为它值得指出。
for y in 0..<height {
        for x in 0..<width {
            let byteIndex = (bytesPerRow * y) + x * bytesPerPixel