Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

概要

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

ポイント

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

ソースコード

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))
  • 例によってお気づきの点があれば気軽にコメントください!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away