Last active
January 17, 2020 12:34
-
-
Save yfujiki/a4b3ba9f5ca58653e953360049849867 to your computer and use it in GitHub Desktop.
ScratchCard implementation inspect scratched area
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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