【发布时间】:2017-04-01 08:01:07
【问题描述】:
我有计算图像 alpha 的函数。但我在 iPhone 5 上崩溃了,在 iPhone 6 及更高版本上运行良好。
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 编码的新手。
【问题讨论】:
-
什么样的崩溃?
-
你总是遍历所有像素,因此你只需要
let alphaOnlyPixels = Array(pixelData.filter{ $0 == 0 }).count -
我在 EXC_BASS_ACCESS 上崩溃了我截屏 --> link
标签: swift image alpha bitmapimage