2017-04-01 432 views
0

我有函數來計算圖像的alpha。但是我爲iPhone 5崩潰,在iPhone 6及更高版本中運行良好。獲取圖像的百分比Swift

private func alphaOnlyPersentage(img: UIImage) -> Float { 

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

    let bitmapBytesPerRow = width 
    let bitmapByteCount = bitmapBytesPerRow * height 

    let pixelData = UnsafeMutablePointer<UInt8>.allocate(capacity: bitmapByteCount) 

    let colorSpace = CGColorSpaceCreateDeviceGray() 

    let context = CGContext(data: pixelData, 
          width: width, 
          height: height, 
          bitsPerComponent: 8, 
          bytesPerRow: bitmapBytesPerRow, 
          space: colorSpace, 
          bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.alphaOnly.rawValue).rawValue)! 

    let rect = CGRect(x: 0, y: 0, width: width, height: height) 
    context.clear(rect) 
    context.draw(img.cgImage!, in: rect) 

    var alphaOnlyPixels = 0 

    for x in 0...Int(width) { 
     for y in 0...Int(height) { 

      if pixelData[y * width + x] == 0 { 
       alphaOnlyPixels += 1 
      } 
     } 
    } 

    free(pixelData) 

    return Float(alphaOnlyPixels)/Float(bitmapByteCount) 
} 

請幫我解決!謝謝。對不起,我是iOS編程的新手。

+0

什麼樣的碰撞? – Sulthan

+0

你總是迭代所有的像素,因此你只需要'let alphaOnlyPixels = Array(pixelData.filter {$ 0 == 0})。count' – Sulthan

+0

我碰到了EXC_BASS_ACCESS我捕獲了屏幕拍攝 - > [link]( http://imgur.com/a/QT3wk) – Quyen

回答

0

...替換爲..<否則您訪問的行和列太多。

注意,崩潰是隨機的,取決於內存的分配方式以及是否有權訪問給定地址處的字節,這些字節位於爲您分配的塊之外。

或更換由簡單的迭代:

for i in 0 ..< bitmapByteCount { 
    if pixelData[i] == 0 { 
     alphaOnlyPixels += 1 
    } 
} 

您還可以使用Data創建您的字節,這將在後面簡化迭代:

var pixelData = Data(count: bitmapByteCount) 

pixelData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in 
    let context = CGContext(data: bytes, 
          width: width, 
          height: height, 
          bitsPerComponent: 8, 
          bytesPerRow: bitmapBytesPerRow, 
          space: colorSpace, 
          bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)! 

    let rect = CGRect(x: 0, y: 0, width: width, height: height) 
    context.clear(rect) 
    context.draw(img.cgImage!, in: rect) 
} 

let alphaOnlyPixels = pixelData.filter { $0 == 0 }.count 
+0

讓pixelData = UnsafeMutablePointer .allocate(容量:bitmapByteCount),所以像素數據不符合協議序列,沒有過濾器:( – Quyen

+0

@Quyen你是對的,我的第一個修復仍然有效,我會稍微更新問題的第二部分 – Sulthan

+0

謝謝。 – Quyen