我试图创建一个圆形颜色选择器。我的方法是插入一个图像并使用pixelColors函数来获取该点的颜色。问题是每次点击都会返回错误的颜色。我不知道出了什么问题。
这是图片:
这是我的代码
extension UIImage {
func getPixelColor(x: CGFloat, y: CGFloat) -> UIColor? {
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelIndex: Int = ((Int(self.size.width) * Int(y)) + Int(x)) * 4
let r = CGFloat(data[pixelIndex]) / CGFloat(255.0)
let g = CGFloat(data[pixelIndex+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelIndex+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelIndex+3]) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
以下是我使用此功能的方法
func imageTapped(recognizer: UITapGestureRecognizer) {
let thePoint = recognizer.location(in: view)
let color = imageView.image?.getPixelColor(x: thePoint.x, y: thePoint.y)
print(color)
答案 0 :(得分:1)
尝试使用以下功能获取颜色触摸这个对我来说很好用
//MARK: Get Pixel color on touch
/**
This function is Read data from CSV File
- parameter point: CGPoint Touch Point
- parameter sourceView: View to Detect in
- returns: UIColor
*/
class func getPixelColorAtPoint(point:CGPoint, sourceView: UIView) -> UIColor
{
let pixel = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context!.translateBy(x: -point.x, y: -point.y)
sourceView.layer.render(in: context!)
let color:UIColor = UIColor(red: CGFloat(pixel[0])/255.0,
green: CGFloat(pixel[1])/255.0,
blue: CGFloat(pixel[2])/255.0,
alpha: CGFloat(pixel[3])/255.0)
pixel.deallocate(capacity: 4)
return color
}
用法:
//here get location as CGPoint and just pass it in function
let point = sender.location(in: sender.view)
//For example take reference Color
let color = self.getPixelColorAtPoint(point: point, sourceView: self.GramPieChart)
//self.gramPieChart is my View created from which I need to get the color at touch pass your ImageView here
现在比较
if (color.isEqual(UIColor.init(red: 230/255, green: 53/255, blue: 42/255, alpha: 1.0)))
{
//Required Operation here
}
Or directly
if (color.isEqual(UIColor.init(red: 230/255, green: 53/255, blue: 42/255, alpha: 1.0)))
{
//Required Operation here
}
if (color == UIColor.red)
{
//Required Operation here
}