如何强制PKDrawing始终表现为浅色模式下的行为?
强制PKDrawing始终按浅色模式规则生成图像
嘿,我刚好解决过这个问题!要让PKDrawing不管当前系统是深色还是浅色模式,都输出黑笔迹+透明背景的图像,这里有两个亲测有效的方案:
方案1:临时切换Trait Collection渲染(最稳妥)
PKDrawing的笔迹颜色会跟着当前环境的traitCollection走,所以我们可以临时把渲染环境切换到浅色模式,生成图像后再自动切回去,完美复刻浅色模式的渲染逻辑:
Objective-C 代码:
// 先保存当前的 trait 配置 UITraitCollection *originalTrait = [UITraitCollection currentTraitCollection]; // 创建浅色模式的 trait 配置 UITraitCollection *lightTrait = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight]; // 临时切换到浅色模式执行渲染 [UITraitCollection performCurrentTraitCollection:lightTrait actions:^{ UIImage *lightStyleImage = [yourDrawing imageFromRect:yourDrawing.bounds scale:[UIScreen mainScreen].scale]; // 在这里处理生成好的浅色模式图像 }]; // 不用手动切回原模式,performCurrentTraitCollection 会自动恢复
Swift 代码:
// 保存当前的 trait 配置 let originalTrait = UITraitCollection.current // 创建浅色模式的 trait 配置 let lightTrait = UITraitCollection(userInterfaceStyle: .light) // 临时切换环境渲染图像 UITraitCollection.performCurrentTraitCollection(lightTrait) { let lightStyleImage = yourDrawing.image(from: yourDrawing.bounds, scale: UIScreen.main.scale) // 处理生成的图像 } // 自动恢复原环境,无需额外操作
这个方法的优势是完全遵循系统浅色模式的渲染规则,不管是默认笔迹还是自适应颜色的笔迹,都会正确显示成浅色模式下的效果,不会出现颜色偏差。
方案2:手动指定背景色(适合简单场景)
如果你的需求只是要透明背景+黑色笔迹,也可以直接用带背景色参数的渲染方法,不过要注意:这个方法只适合笔迹都是默认自适应颜色的情况,如果有自定义颜色的笔迹,可能会受影响。
Objective-C 代码:
// 直接指定透明背景,结合临时切换trait的思路更稳妥 UITraitCollection *lightTrait = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight]; [UITraitCollection performCurrentTraitCollection:lightTrait actions:^{ UIImage *lightStyleImage = [yourDrawing imageFromRect:yourDrawing.bounds scale:[UIScreen mainScreen].scale withBackgroundColor:[UIColor clearColor]]; }];
Swift 代码:
let lightTrait = UITraitCollection(userInterfaceStyle: .light) UITraitCollection.performCurrentTraitCollection(lightTrait) { let lightStyleImage = yourDrawing.image(from: yourDrawing.bounds, scale: UIScreen.main.scale, backgroundColor: .clear) }
小提醒
- 如果是在后台线程渲染,不用担心线程安全问题,
performCurrentTraitCollection:本身是线程安全的,可以放心使用。 - 如果你有自定义颜色的笔迹,方案1会保留这些颜色,只有系统自适应的笔迹会切换成浅色模式的样式,完全符合需求。
内容的提问来源于stack exchange,提问作者Holtwick




