Skip to content

Instantly share code, notes, and snippets.

@ohkawa
Last active July 13, 2018 20:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohkawa/17fa56656d1a7594f2a5 to your computer and use it in GitHub Desktop.
Save ohkawa/17fa56656d1a7594f2a5 to your computer and use it in GitHub Desktop.
[Swift] 画像の特定のピクセルの色を調べる ref: http://qiita.com/ohkawa/items/71db370b5a6b75bae517
import UIKit
let pixelDataByteSize = 4
extension UIImage {
func getColor(pos: CGPoint) -> UIColor {
let imageData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
let data : UnsafePointer = CFDataGetBytePtr(imageData)
let scale = UIScreen.mainScreen().scale
let address : Int = ((Int(self.size.width) * Int(pos.y * scale)) + Int(pos.x * scale)) * pixelDataByteSize
let r = CGFloat(data[address])
let g = CGFloat(data[address+1])
let b = CGFloat(data[address+2])
let a = CGFloat(data[address+3])
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
let image = UIImage(named: "myImage")
let pixelColor = image!.getColor(CGPointMake(100, 100))
@ohkawa
Copy link
Author

ohkawa commented Oct 3, 2015

License is Completely Free
You can use this in any case without copyright notice.

@AmitaiB
Copy link

AmitaiB commented Jul 13, 2018

In Swift 4.x:

fileprivate let pixelDataByteSize = 4

extension UIImage {
    func getColor(pos: CGPoint) -> UIColor? {

        guard let imageData = cgImage?.dataProvider?.data else { return nil }
        
        let data : UnsafePointer = CFDataGetBytePtr(imageData)
        let scale = UIScreen.main.scale
        let address : Int = ((Int(size.width) * Int(pos.y * scale)) + Int(pos.x * scale)) * pixelDataByteSize
        let r = CGFloat(data[address])
        let g = CGFloat(data[address+1])
        let b = CGFloat(data[address+2])
        let a = CGFloat(data[address+3])

        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
}

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment