2017-11-29 2 views
0

원 색상 선택 도구를 만들려고합니다. 내 접근 방식은 이미지를 삽입하고 pointColors 함수를 사용하여 점의 색상을 얻는 것입니다. 문제는 클릭 할 때마다 잘못된 색상을 반환한다는 것입니다. 나는 틀린 것을 모른다.원 색상 선택 도구를 만듭니다.

다음
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

하면 얻을 기능 이하로 사용해보십시오이 기능을 사용하는 방법입니다 여기에

enter image description here

내 코드입니다 : 여기

은 이미지입니다 이 하나가 작동하는 터치에 대한 색상 괜찮아요 나를 위해

012 사용 3,516,
//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

관련 문제