FlexMonkey 的ImageCompareDemo是从 facebook 的C++ 中的ios-snapshot-test-case到 Swift 的不完整移植。它遗漏了每像素比较的最后一部分。我的是 Swift 4,这是整个功能:
static func compareWithImage(reference:CGImage, target:CGImage, tolerance:CGFloat) -> Bool {
guard reference.width == target.width && reference.height == target.height else { return false }
let referenceImageSize = CGSize(width:CGFloat(reference.width), height:CGFloat(reference.height))
let targetImageSize = CGSize(width:CGFloat(target.width), height:CGFloat(target.height))
let minBytesPerRow = min(reference.bytesPerRow, target.bytesPerRow)
let referenceImageSizeBytes = Int(referenceImageSize.height) * minBytesPerRow
let referenceImagePixels = calloc(1, referenceImageSizeBytes)
let targetImagePixels = calloc(1, referenceImageSizeBytes)
let referenceImageCtx = CGContext(data: referenceImagePixels,
width: Int(referenceImageSize.width),
height: Int(referenceImageSize.height),
bitsPerComponent: reference.bitsPerComponent,
bytesPerRow: minBytesPerRow,
space: reference.colorSpace!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
let targetImageCtx = CGContext(data: targetImagePixels,
width: Int(targetImageSize.width),
height: Int(targetImageSize.height),
bitsPerComponent: target.bitsPerComponent,
bytesPerRow: minBytesPerRow,
space: target.colorSpace!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
guard let referenceImageContext = referenceImageCtx, let targetImageContext = targetImageCtx else {
return false
}
referenceImageContext.draw(reference, in:CGRect(x:0, y:0, width:referenceImageSize.width, height:referenceImageSize.height))
targetImageContext.draw(target, in:CGRect(x:0, y:0, width:targetImageSize.width, height:targetImageSize.height))
var imageEqual = true
if(tolerance == 0) {
imageEqual = (memcmp(referenceImagePixels, targetImagePixels, referenceImageSizeBytes) == 0)
} else {
let pixelCount = Int(referenceImageSize.width * referenceImageSize.height)
let p1 = convertUMRPtoUInt32Array(pointer:referenceImagePixels!, length:referenceImageSizeBytes)
let p2 = convertUMRPtoUInt32Array(pointer:targetImagePixels!, length:referenceImageSizeBytes)
var percent:CGFloat = 0
var numDiffPixels = 0
for n in 0..<pixelCount {
if(p1[n] != p2[n]) {
numDiffPixels += 1
percent = CGFloat(numDiffPixels) / CGFloat(pixelCount)
if (percent > tolerance) {
imageEqual = false;
break;
}
}
}
//print(percent)
}
referenceImagePixels?.deallocate(bytes:referenceImageSizeBytes, alignedTo:1)
targetImagePixels?.deallocate(bytes: referenceImageSizeBytes, alignedTo: 1)
return imageEqual
}