首页 > 解决方案 > 断言从 UIGraphics 生成的 UIImage 都是红色的

问题描述

不久前,我发现了一些根据状态更改 UIButton 背景颜色的代码。代码如下所示:

extension UIButton {
    func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(colorImage, for: state)     
    }
}

现在我想知道如何正确测试此功能。有任何想法吗?

谢谢

标签: swiftxctest

解决方案


  • 调用你的扩展方法
  • 调用.backgroundImage(for:)获取 UIImage
  • 将 UIImage 渲染为像素
  • 比较像素颜色值

推荐阅读