44
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift] 画像の特定のピクセルの色を調べる

Last updated at Posted at 2015-10-03

概要

  • 画像の特定のピクセルの色を調べる(クリックした場所のピクセル色とか)

ポイント

  • CFDataGetBytePtrの戻り値がUnsafePointerで、中身がバイナリデータ(?)なので取得したいピクセルのデータが入っている場所を計算してアクセスする
  • 1pixel分のデータは4Byteで、1ByteずつR,G,B,Aの色情報になっている
  • Retinaの考慮が必要(非Retinaの1pixelが、Retinaだと4pixel分のデータ量になるのでアクセスする位置がズレる)

ソースコード

UIImage+PixelColor.swift
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)
    }
}

使い方

  • UIImageのExtensionとして作れば、こんな感じで使えます
Useage.swift
let image = UIImage(named: "myImage")
let pixelColor = image!.getColor(CGPointMake(100, 100))
  • 例によってお気づきの点があれば気軽にコメントください!
44
37
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?