我有函數來計算圖像的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編程的新手。
什麼樣的碰撞? – Sulthan
你總是迭代所有的像素,因此你只需要'let alphaOnlyPixels = Array(pixelData.filter {$ 0 == 0})。count' – Sulthan
我碰到了EXC_BASS_ACCESS我捕獲了屏幕拍攝 - > [link]( http://imgur.com/a/QT3wk) – Quyen