如何根据背景颜色自动更改视图的透明颜色

时间:2020-06-24 11:28:16

标签: ios swift xcode uiimage uicolor

我想在uiimageview上显示一个半透明的文本字段。我无法为文本字段选择静态颜色,因为有些图像很亮而另一些图像很暗。我想根据其后面的颜色自动调整文本字段的颜色。有一个简单的解决方案吗?

UPD: 我想要达到的效果是: 如果UIImage在应放置我的文本字段的位置较暗,则将文本字段的背景色设置为不透明度为0.5的白色。 如果UIImage浅,应将其放置在我的文本字段中,请将文本字段的背景色设置为不透明度为0.5的黑色。

所以我想以某种方式计算uiimageview的平均颜色,该颜色要放在我的文本字段中,然后检查它是浅还是暗。我不知道如何获取uiimageview特定部分的屏幕截图并获取其平均颜色。我希望对其进行优化。我猜与UIGraphicsImageRenderer一起工作不是一个好选择,这就是为什么我问这个问题。我知道如何使用UIGraphicsImageRenderer做到这一点,但我认为我的方法不够好。

1 个答案:

答案 0 :(得分:2)

图像的“亮度”不是直截了当的事情。您可能会或可能不会觉得合适。

如果您搜索determine brightness of an image,则会找到大量文档-可能比您想要的更多。

一种计算像素“亮度”的常用方法是使用以下各项的总和:

red component   * 0.299
green component * 0.587
blue component  * 0.114

这是因为我们在不同的“亮度”级别上会感知到不同的颜色。

因此,您需要遍历要放置标签(或textField)的图像区域中的每个像素,获取平均亮度,然后确定“暗”和“亮”。

例如,使用此背景图片:

enter image description here

我生成了一个5 x 8的标签网格,循环获取每个标签框架下矩形中图像的“亮度”,然后根据亮度计算设置背景和文本颜色(值范围从0到255,所以我用<127是深色,> = 127是浅):

enter image description here

这是我使用的代码:

extension CGImage {
    var brightness: Double {
        get {
            // common formula to get "average brightness"
            let bytesPerPixel = self.bitsPerPixel / self.bitsPerComponent
            let imageData = self.dataProvider?.data
            let ptr = CFDataGetBytePtr(imageData)
            var x = 0
            var p = 0
            var result: Double = 0
            for _ in 0..<self.height {
                for _ in 0..<self.width {
                    let r = ptr![p+0]
                    let g = ptr![p+1]
                    let b = ptr![p+2]
                    result += (0.299 * Double(r) + 0.587 * Double(g) + 0.114 * Double(b))
                    p += bytesPerPixel
                    x += 1
                }
            }
            let bright = result / Double (x)
            return bright
        }
    }
}
extension UIImage {
    // get the "brightness" of self (entire image)
    var brightness: Double {
        get {
            return (self.cgImage?.brightness)!
        }
    }

    // get the "brightness" in a sub-rect of self
    func brightnessIn(_ rect: CGRect) -> Double {
        guard let cgImage = self.cgImage else { return 0.0 }
        guard let croppedCGImage = cgImage.cropping(to: rect) else { return 0.0 }
        return croppedCGImage.brightness
    }
}

class ImageBrightnessViewController: UIViewController {
    
    let imgView: UIImageView = {
        let v = UIImageView()
        v.contentMode = .center
        v.backgroundColor = .green
        v.clipsToBounds = true
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var labels: [UILabel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // load an image
        guard let img = UIImage(named: "bkg640x360") else { return }

        imgView.image = img

        let w = img.size.width
        let h = img.size.height
        
        // set image view's width and height equal to img width and height
        view.addSubview(imgView)
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            imgView.widthAnchor.constraint(equalToConstant: w),
            imgView.heightAnchor.constraint(equalToConstant: h),
            imgView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            imgView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
        ])

        // use stack views to create a 5 x 8 grid of labels
        let outerStackView: UIStackView = {
            let v = UIStackView()
            v.translatesAutoresizingMaskIntoConstraints = false
            v.axis = .horizontal
            v.spacing = 32
            v.distribution = .fillEqually
            return v
        }()

        for _ in 1...5 {
            let vStack = UIStackView()
            vStack.axis = .vertical
            vStack.spacing = 12
            vStack.distribution = .fillEqually
            for _ in 1...8 {
                let label = UILabel()
                label.textAlignment = .center
                vStack.addArrangedSubview(label)
                labels.append(label)
            }
            outerStackView.addArrangedSubview(vStack)
        }
        
        let padding: CGFloat = 12.0

        imgView.addSubview(outerStackView)
        NSLayoutConstraint.activate([
            outerStackView.topAnchor.constraint(equalTo: imgView.topAnchor, constant: padding),
            outerStackView.leadingAnchor.constraint(equalTo: imgView.leadingAnchor, constant: padding),
            outerStackView.trailingAnchor.constraint(equalTo: imgView.trailingAnchor, constant: -padding),
            outerStackView.bottomAnchor.constraint(equalTo: imgView.bottomAnchor, constant: -padding),
        ])
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        guard let img = imgView.image else {
            return
        }
        labels.forEach { v in
            if let sv = v.superview {
                // convert label frame to imgView coordinate space
                let rect = sv.convert(v.frame, to: imgView)
                // get the "brightness" of that rect from the image
                //  it will be in the range of 0 - 255
                let d = img.brightnessIn(rect)
                // set the text of the label to that value
                v.text = String(format: "%.2f", d)
                // just using 50% here... adjust as desired
                if d > 127.0 {
                    // if brightness is than 50%
                    //  black translucent background with white text
                    v.backgroundColor = UIColor.black.withAlphaComponent(0.5)
                    v.textColor = .white
                } else {
                    // if brightness is greater than or equal to 50%
                    //  white translucent background with black text
                    v.backgroundColor = UIColor.white.withAlphaComponent(0.5)
                    v.textColor = .black
                }
            }
        }
    }
}

如您所见,获取照片区域的平均值时,您对结果往往并不完全满意。这就是为什么看到一个或另一个具有相反的顺序并在框架周围出现阴影或发光的原因。