Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
36
Help us understand the problem. What is going on with this article?
@ohkawa

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

More than 5 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))
  • 例によってお気づきの点があれば気軽にコメントください!
36
Help us understand the problem. What is going on with this article?
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
ohkawa

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
36
Help us understand the problem. What is going on with this article?