我正在尝试为我的照片编辑器应用程序创建橡皮擦工具
Photoshop
(或者可以从图像中删除已定义的颜色),例如,用户将在图像上绘制具有所需颜色的线条,我的功能将在触摸立即结束后处理图像。
我创建了一个方法,它可以很好地与一些颜色,如白色,黑色,黄色等,但当我选择颜色与0.5阿尔法它不工作的理想!
extension UIImage {
func getImageRemovedDefinedColor(choosedColor: UIColor) -> UIImage? {
let image = UIImage(data: self.jpegData(compressionQuality: 1.0)!)!
let rawImageRef: CGImage = image.cgImage!
let components = choosedColor.cgColor.components!
var colorMasking: [CGFloat] = []
var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
if choosedColor.isEqual(UIColor.white) {
colorMasking = [222, 255, 222, 255, 222, 255]
} else if choosedColor.isEqual(UIColor.black) {
colorMasking = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
} else {
if components.count > 3 {
red = components[0]
green = components[1]
blue = components[2]
alpha = components[3]
red = red * 255.0
green = green * 255.0
blue = blue * 255.0
alpha = alpha * 255.0
let redRange: [CGFloat] = {
return [max(red - (alpha / 2.0), 0.0), min(red + (alpha / 2.0), 255.0)]
}()
let greenRange: [CGFloat] = {
return [max(green - (alpha / 2.0), 0.0), min(green + (alpha / 2.0), 255.0)]
}()
let blueRange: [CGFloat] = {
return [max(blue - (alpha / 2.0), 0.0), min(blue + (alpha / 2.0), 255.0)]
}()
colorMasking = [redRange[0], redRange[1], greenRange[0], greenRange[1], blueRange[0], blueRange[1]]
}
}
print(colorMasking)
UIGraphicsBeginImageContext(image.size);
let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
let result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result
}
注:
也许我做这个工具的方式是完全错误的,如果你有关于“我们怎样才能用Swift创建橡皮擦工具”的另一个想法,请分享。