前阵子清明节为哀悼疫情中去世去的同胞和战士们,全国娱乐设施停业一天,各大厂商的 app 也都启动了灰度色盲模式的
类似效果
下面是本文要实现的效果
因此方案并不完全成熟,本文只讲思路不提供demo
类似效果在安卓里有多种实现方案
第一种是拿系统色盲模式(iOS 拿不到)
第二种就是遍历 view 了,此文方案是这种思路
一、一个全局控制的单例
单利需要的内容有:是否置灰的状态、开启灰色配置的方法、 多个weakMemory 的NSHashTable保存要处理的 view 们
// 启动方法,要处理所有视图交换方法
public func launch() {
isGray = true
UIImageView.ZHGrayStyleImageViewSwizzleMethord
UIView.ZHGrayStyleUIViewswizzleMethord
CALayer.ZHGrayStyleUIViewswizzleMethord
UIImage.ZHGrayStyleImageSwizzleMethord
UITabBar.ZHGrayStyleTabbarSwizzleMethord
UILabel.ZHGrayStyleLabelSwizzleMethord
}
交换方法代码
extension NSObject {
@objc dynamic func zh_setAssociatedObject(key: UnsafeRawPointer, value: Any?) {
objc_setAssociatedObject(self, key, value, .OBJC_ASSOCIATION_RETAIN)
}
@objc dynamic func zh_getAssociatedObject(key: UnsafeRawPointer) -> Any? {
return objc_getAssociatedObject(self, key)
}
static func zh_swizzle(originalSelector: Selector, swizzledSelector: Selector) {
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
guard (originalMethod != nil && swizzledMethod != nil) else {
return
}
if class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
}
二、交换方法,只展示一个例子(要处理的有 View的 backgroundColor、layer 的 backgroundColor 和 shadowColor、label 的 textColor、tabBar 的 tintColor 等)
// static let xxx: Void = {}()保证只执行一次
static let ZHGrayStyleUIViewswizzleMethord: Void = {
zh_swizzle(originalSelector: #selector(getter: UIView.backgroundColor), swizzledSelector: #selector(getter: UIView.myBackgroundColor))
zh_swizzle(originalSelector: #selector(setter: UIView.backgroundColor), swizzledSelector: #selector(setter: UIView.myBackgroundColor))
}()
var cacheBackgroundColor: UIColor? {
set {
zh_setAssociatedObject(key: &ZHGrayStlyeBackgroundColorKey, value: newValue)
}
get {
return zh_getAssociatedObject(key: &ZHGrayStlyeBackgroundColorKey) as? UIColor
}
}
@objc
open var myBackgroundColor: UIColor? {
set {
ZHGrayStyle.instance.append(self)
if ZHGrayStyle.instance.isGray, let newValue = newValue {
cacheBackgroundColor = newValue
self.myBackgroundColor = newValue.getGrayColor()
} else {
cacheBackgroundColor = newValue?.getGrayColor() ?? nil
self.myBackgroundColor = newValue
}
}
get {
return self.myBackgroundColor
}
}
三、Color 的 grayColor 算法(CGColor 类似)
public func getGrayColor() -> UIColor {
let rgb = getRGB()
guard rgb.r != rgb.g && rgb.r != rgb.b else { return self }
let rColor = rgb.r * 0.299
let gColor = rgb.g * 0.587
let bColor = rgb.b * 0.114
let gray = rColor + gColor + bColor
return .init(red: gray, green: gray, blue: gray, alpha: 1)
}
public func getGrayColor(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
// 不处理浮点数也可以*299,最后 gray 的和 / 1000这样算
let rColor = r * 0.299
let gColor = g * 0.587
let bColor = b * 0.114
let gray = rColor + gColor + bColor
return .init(red: gray, green: gray, blue: gray, alpha: 1)
}
public func getRGB() -> (r: CGFloat, g: CGFloat, b: CGFloat) {
var RColor: CGFloat = 0
var GColor: CGFloat = 0
var BColor: CGFloat = 0
if let components = self.cgColor.components, components.count == 4 {
RColor = components[0]
GColor = components[1]
BColor = components[2]
}
return (RColor, GColor, BColor)
}
四、到此,我们已经完成了大部分工作,剩下的也是最难啃的骨头--UIImage
4.1、要处理 UIImage,首先需要了解位图的格式,在此不做阐述,推荐地址:
https://www.jianshu.com/p/362c2f03d378
4.2、在了解了位图之后,我们可以处理位图
public func grayImage() -> UIImage? {
// 获得宽度和高度数值
let width = Int(size.width)
let height = Int(size.height)
// 创建灰度色彩空间对象,各种设备对待颜色的方式都不一样,颜色必须有一个相关的色彩空间
let spaceRef = CGColorSpaceCreateDeviceGray()
// 参数data指向渲染的绘制内存的地址,bitsOerComponent表示内存中像素的每个组件的位数,bytesPerRow表示每一行在内存中占的比特数,space表示使用的颜色空间,bitmapInfo表示是否包含alpha通道
// CGBitmapInfo().rawValue
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: spaceRef, bitmapInfo: CGBitmapInfo().rawValue) else {
return nil
}
// 然后创建一个和原视图同样尺寸的空间
let rect = CGRect(x: 0, y: 0, width: width, height: height)
// 在灰度上下文中画入图片
// context.alpha
guard let cgImage = cgImage else {
return nil
}
context.draw(cgImage, in: rect)
// 从上下文中获取并生成专为灰度的图片
if let cgImage = context.makeImage() {
let grayImage = UIImage.init(cgImage: cgImage)
return grayImage
}
return nil
}
4.3、图片灰度处理后会发现png的透明底会变成黑色,如图
时间原因,在此只提供 oc 处理方法,把黑底转为透明:
+ (UIImage*)imageToTransparent:(UIImage*) image
{
// 分配内存
const int imageWidth = image.size.width;
const int imageHeight = image.size.height;
size_t bytesPerRow = imageWidth * 4;
uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
// 创建context
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
// 遍历像素
int pixelNum = imageWidth * imageHeight;
uint32_t* pCurPtr = rgbImageBuf;
for (int i = 0; i < pixelNum; i++, pCurPtr++)
{
uint8_t* ptr = (uint8_t*)pCurPtr;
if (ptr[3] < 50 && ptr[3] < 50 && ptr[1] < 50) {
ptr[0] = 0;
} else {
// 灰度算法
uint8_t gray = ptr[3] * 0.299 + ptr[2] * 0.587 + ptr[1] * 0.114;
ptr[3] = gray; //0~255
ptr[2] = gray;
ptr[1] = gray;
}
}
// 将内存转成image
CGDataProviderRef dataProvider =CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight,8, 32, bytesPerRow, colorSpace,
kCGImageAlphaLast |kCGBitmapByteOrder32Little, dataProvider,
NULL, true,kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);
UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
// 释放
CGImageRelease(imageRef);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return resultUIImage;
}
void ProviderReleaseData (void *info, const void *data, size_t size)
{
free((void*)data);
}
五、总结
本文主要是运用了 runtime 去 hook 各种要处理的视图的相关方法,例如 init,例如 backgroundColor,去进行灰度处理操作,还要对 bitmap 位图有一定的了解去处理图片(大多数是图片置灰)