Last active
July 13, 2018 20:20
-
-
Save ohkawa/17fa56656d1a7594f2a5 to your computer and use it in GitHub Desktop.
[Swift] 画像の特定のピクセルの色を調べる ref: http://qiita.com/ohkawa/items/71db370b5a6b75bae517
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let image = UIImage(named: "myImage") | |
let pixelColor = image!.getColor(CGPointMake(100, 100)) |
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
License is Completely Free
You can use this in any case without copyright notice.