I have displayed an image with 50% alpha in UIImageview. My requirement is to highlight(alpha 100%) some parts(outlined with bezierpath) of UIImage. Here are steps I tried.
- drawing image in UIGraphicsGetCurrentContext
- outlining the desired parts using bezier path.
- extract new image using this code- let newImage = UIGraphicsGetImageFromCurrentImageContext
I tried process the newImage using below code -
`func processPixelsInImage(_ image: UIImage) -> UIImage? { guard let inputCGImage = image.cgImage else { //print("unable to get cgImage") return nil } let colorSpace = CGColorSpaceCreateDeviceRGB() let width = inputCGImage.width let height = inputCGImage.height let bytesPerPixel = 4 let bitsPerComponent = 8 let bytesPerRow = bytesPerPixel * width let bitmapInfo = RGBA32.bitmapInfo
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
//print("unable to create context")
return nil
}
context.draw(inputCGImage, in: CGRect(x: 0, y: 0, width: width, height: height))
guard let buffer = context.data else {
//print("unable to get context data")
return nil
}
let pixelBuffer = buffer.bindMemory(to: RGBA32.self, capacity: width * height)
//let white = RGBA32(red: 255, green: 255, blue: 255, alpha: 255)
//let clear = RGBA32(red: 0, green: 0, blue: 0, alpha: 1)
for row in 0 ..< Int(height) {
for column in 0 ..< Int(width) {
let offset = row * width + column
let color = image.getPixelColor(pos: CGPoint(x: row, y: column))
let newpixelcolor = RGBA32(red: UInt8(color.0 * 255), green: UInt8(color.1 * 255), blue: UInt8(color.2 * 255), alpha: 1)
for path in bezierPathArray {
if path.contains(CGPoint(x: row, y: column)) {
pixelBuffer[offset] = newpixelcolor//color.withAlphaComponent(1.0)
}
}
}
}
let outputCGImage = context.makeImage()!
let outputImage = UIImage(cgImage: outputCGImage, scale: image.scale, orientation: image.imageOrientation)
return outputImage
}`
Problem with above code - consuming 100% CPU, too much memory (50 mb for 760*1280 image).
I am thinking to process the pixels using Metal framework(utilising GPU instead of CPU)
How I can do it? Pls help. Any help would be highly appreciated