我正在使用CAGradientLayer添加一个渐变到我的UIView。我正在设置渐变为纯红色测试,当我检查显示的颜色时,它显示的RGB值与我指定的不同。有没有方法可以确保渐变显示我设置的颜色?
let gradientLayer2 = CAGradientLayer()
gradientLayer2.frame.size = colourPickerView.frame.size
gradientLayer2.colors = [
UIColor(red: 1.00, green: 0.00, blue: 0.00, alpha: 1.00).cgColor
UIColor(red: 1.00, green: 0.00, blue: 0.00, alpha: 1.00).cgColor,
]
gradientLayer2.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer2.endPoint = CGPoint(x: 1, y: 0)
gradientLayer2.cornerRadius = 20
colourPickerView.layer.insertSublayer(gradientLayer2, at: 0)
这将红色显示为:<CGColor 0x283c8e400> [<CGColorSpace 0x283c989c0> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 1 0.14902 0 1 )
(请注意,绿色值显示为“0.14902”)
当我添加一个纯色的背景色到图层,而不是一个梯度,它确实显示正确的RGB值。
let layer = CALayer()
layer.frame.size = colourPickerView.frame.size
layer.backgroundColor = UIColor(red: 1.00, green: 0.00, blue: 0.00, alpha: 1.00).cgColor
colourPickerView.layer.insertSublayer(layer, at: 0)
下面是我用来获取某个像素的颜色的代码:
extension UIView {
func colorOfPointView(point: CGPoint) -> UIColor {
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
var pixelData: [UInt8] = [0, 0, 0, 0]
let context = CGContext(data: &pixelData, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context!.translateBy(x: -point.x, y: -point.y)
self.layer.render(in: context!)
let red: CGFloat = CGFloat(pixelData[0]) / CGFloat(255.0)
let green: CGFloat = CGFloat(pixelData[1]) / CGFloat(255.0)
let blue: CGFloat = CGFloat(pixelData[2]) / CGFloat(255.0)
let alpha: CGFloat = CGFloat(pixelData[3]) / CGFloat(255.0)
let color: UIColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
1条答案
按热度按时间efzxgjgh1#
奇怪!这是唯一涉及这部分代码的代码吗?我刚刚测试过,得到了真实的结果:
将这段代码复制并粘贴到一个新的Xcode项目中,然后检查是否仍然得到错误的结果。