[英]How to change color for point in UIImage?
I have a code that changes the color of a certain point in an image to transparent.我有一个代码可以将图像中某个点的颜色更改为透明。
func processByPixel(in image: UIImage, byPoint: CGPoint) -> 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("Cannot create context!"); return nil
}
context.draw(inputCGImage, in: CGRect(x: 0, y: 0, width: width, height: height))
guard let buffer = context.data else { print("Cannot get context data!"); return nil }
let pixelBuffer = buffer.bindMemory(to: RGBA32.self, capacity: width * height)
let offset = Int(byPoint.x) * width + Int(byPoint.y)
pixelBuffer[offset] = .transparent
let outputCGImage = context.makeImage()!
let outputImage = UIImage(cgImage: outputCGImage, scale: image.scale, orientation: image.imageOrientation)
return outputImage
}
By tapping on the picture, I calculate the point on which it was clicked and pass it to this function.通过点击图片,我计算点击它的点并将其传递给这个函数。 The problem is that the color changes slightly with the offset.
问题是颜色随着偏移量略有变化。 For example I will pass CGPoint(x: 0, y:0) but change color to 0, 30
例如,我将传递 CGPoint(x: 0, y:0) 但将颜色更改为 0, 30
I think that the offset variable is not calculated correctly我认为偏移变量计算不正确
Calculate the offset like this:像这样计算偏移量:
let offset = Int(byPoint.y) * width + Int(byPoint.x)
It is the number of vertical lines times line length plus x.它是垂直线的数量乘以线的长度加上 x。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.