gpt4 book ai didi

swift - 每次用户选择另一种颜色时如何更改对比度?

转载 作者:行者123 更新时间:2023-11-28 13:26:22 25 4
gpt4 key购买 nike

我知道在 JavaScript 中有一个函数可以根据当前选择的颜色改变对比度:


function getHigherContrast(r, g, b) {
const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
return (yiq >= 128) ? '#000000' : '#FFFFFF';
}

如何将此函数重写为 Swift-Code,以便每次用户选择另一种颜色时对比度都会发生变化: enter image description here


override func viewDidLoad() {
super.viewDidLoad()

self.view.addSubview(colorPicker)
colorPicker.translatesAutoresizingMaskIntoConstraints = false
colorPicker.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor).isActive = true
colorPicker.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor).isActive = true
colorPicker.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor).isActive = true
colorPicker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action:#selector(handleDone(sender:)))

colors.append((colorTitle: "rot", color: UIColor.red))
colors.append((colorTitle: "gelb", color: UIColor.yellow))
colors.append((colorTitle: "grün", UIColor.green))
colors.append((colorTitle: "schwarz", UIColor.black))

colorPicker.delegate = self
colorPicker.dataSource = self
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return colors.count
}

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
return NSAttributedString(string: colors[row].colorTitle, attributes: [NSAttributedStringKey.foregroundColor: colors[row].color])
}

@objc func handleDone(sender: AnyObject?) {
if let d = delegate {
d.colorPicked(color: colors[colorPicker.selectedRow(inComponent: 0)].color)
}
dismiss(animated: true)
}

Here是该类的完整源代码。

最佳答案

你可以试试

func getHigherContrast(r:Int, g:Int, b:Int) -> UIColor {
let yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000
return yiq >= 128 ? UIColor.black : UIColor.white
}

关于swift - 每次用户选择另一种颜色时如何更改对比度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58287503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com