我有函数来计算图像的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