10
11

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.

iOS/Swift : UIViewに実際に描画されているピクセルの色を取得する

Last updated at Posted at 2016-03-14

目的

UIView上の任意の位置(ローカルx,y座標)のピクセルの色を知りたい。

実装

下記のように画素配列を取り出してアクセスする。画素成分の並び順に注意。常に R, G, B, A という順序で並んでいるわけではない。(詳しくはコメント欄参照)

// view 上の位置 (x,y)の画素にアクセス
UIGraphicsBeginImageContext(view.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let imgCtx = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(imgCtx!.CGImage))
// 画素バッファを得る
let pixelBuf = CFDataGetBytePtr(pixelData)

// 画素アドレス(バッファ内インデクス)を求める
let pixelAddr = ((view.frame.size.width * y) + x) * 4   // 1 Pixel==4 Byte
// 画素成分が、Green, Blue, Red, Alpha の順に並んでいる場合
let green = CGFloat(pixelBuf[ pixelAddr ])/255.0
let blue  = CGFloat(pixelBuf[ pixelAddr+1 ])/255.0
let red   = CGFloat(pixelBuf[ pixelAddr+2 ])/255.0
let alpha = CGFloat(pixelBuf[ pixelAddr+3 ])/255.0

// UIColor オブジェクト作成
let color = UIColor(red:red, green:green, blue:blue, alpha:alpha)

10
11
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
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?