在这个问题中,我需要你们提供一些算法或逻辑方面的帮助。如果这在某些方面是可能的……
因此,我必须开发/编写一个函数来接收温度值(C° 或 F°)作为输入,并根据这张图片中的温度返回特定颜色。例如,如果我们输入 0C°,颜色值应返回为青色(十六进制值:29eff6 或 RGB:41,239,246)
引用图片
我在不同的网站上搜索了很多,但没有找到与此相关的内容。有kelvin color 1000K° plus 的代码,这些与我的问题无关。
如有任何帮助,我们将不胜感激。
最佳答案
这是我在评论中提到的一个简单/虚假解决方案的示例:
import UIKit
func mapValue(value: CGFloat, inMin: CGFloat, inMax: CGFloat, outMin: CGFloat, outMax: CGFloat) -> CGFloat {
// when the input value is lower than `inMin` use `inMin`
// when the input value is bigger than `inMax` use `inMax`
let value = max(min(value, inMax), inMin)
let div = inMax - inMin
guard div > 0 else {
return inMin
}
return (value - inMin) / div * (outMax - outMin) + outMin
}
func getColor(for degreesCelsius: CGFloat) -> UIColor {
// your color-range-image
let rangeImage = UIImage(named: "range.png")!
// the size of your color-range-image
let imageSize = rangeImage.size
let inMin: CGFloat = -50 // the lowest value as seen from the image
let inMax: CGFloat = 55 // the highest value as seen from the image
// the mapped input value
let mappedInput = mapValue(value: degreesCelsius,
inMin: inMin, inMax: inMax,
outMin: 0, outMax: imageSize.width - 1)
// position of the pixel in the image whose color should be extracted
let pos = CGPoint(x: mappedInput, y: 0)
return rangeImage.getPixelColor(pos: pos)
}
// get the color of 37°C
let color = getColor(for: 37)
要在特定位置提取 UIImage
的 UIColor
,您可以使用:
// taken from https://stackoverflow.com/a/40237504/4511639
extension UIImage {
func getPixelColor(pos: CGPoint) -> UIColor {
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
关于ios - 如何在 iOS 中创建特定于温度的颜色图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49167065/