Skip to content

Instantly share code, notes, and snippets.

@yfujiki
Last active January 17, 2020 12:34
Show Gist options
  • Save yfujiki/a4b3ba9f5ca58653e953360049849867 to your computer and use it in GitHub Desktop.
Save yfujiki/a4b3ba9f5ca58653e953360049849867 to your computer and use it in GitHub Desktop.
ScratchCard implementation inspect scratched area
extension UIView {
func transparentPercentage() -> Double {
let width = Int(bounds.width)
let height = Int(bounds.height)
// 1. Prepare a memory space where you write in RGBA data of the view
var pixelData: [UInt8] = Array<UInt8>(repeating: 0, count: width * height * 4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
// 2. Prepare a context with the RGB space you secured above
guard let context = CGContext(data: &pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return 0 }
// 3. Render the entire view into the context, thereby filling in the `pixelData` variable
self.layer.render(in: context)
let totalArea = width * height
var transparentCount = 0
for x in 0 ..< width {
for y in 0 ..< height {
// 4. Get alpha component and see if it is zero.
let alpha = pixelData[(y * width + x) * 4 + 3]
if alpha == 0 {
transparentCount += 1
}
}
}
return Double(transparentCount) / Double(totalArea) * 100
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment