2017-11-29 4 views
0

円のカラーピッカーを作成しようとしています。私のアプローチは、画像を挿入し、ポイントの色を取得するpixelColors関数を使用することです。問題は、クリックするたびに間違った色が返されることです。私は何が間違っているのか分からない。ここで円のカラーピッカーを作成する

はイメージです。ここ

enter image description here

は私のコードここ

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) 

答えて

2

この機能を使用する方法でありますタッチの色これが動作している私のためのファイン

//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 
    } 
+0

それがうまく働いて、どうもありがとうございました。再度、感謝します! – user8933752

+0

私の答えは働いたのですか? –

+0

はい答えが私のために働いています – user8933752

関連する問題