【问题标题】:Can't get bytes for a non-square image无法获取非方形图像的字节
【发布时间】:2016-08-02 06:00:10
【问题描述】:

我使用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 精灵)时,它才会成功,每当我尝试获取尺寸不相等的图像“光栅”时,我都会得到“索引超出范围” " x = 16 和 y = 0 上 red 的致命错误(对于尺寸为 h:16,w:32 的图像)。有什么办法可以解决这个问题?

提前谢谢你!

【问题讨论】:

  • 澄清一下,我得到了 Swift 版本 here 的解释。它现在也固定在那里。
  • 这将导致数组重新分配的大量开销。如果您预先分配数组,性能会大大提高。事实上,这真的没有理由使用NSMutableArray 而不是原生的Swift Array
  • @AMomchilov 再次,我使用了在post 中介绍的实现。我实际使用的有点不同,是的,我同意,绝对没有理由这样做。
  • 是的,我知道。仍然认为值得指出。

标签: ios swift core-graphics


【解决方案1】:

其实很容易解决,问题就在这里:

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

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

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多