簡體   English   中英

如何在swift中找到UIImage中單個像素的顏色

[英]How to find the colour of an individual pixel in UIImage in swift

我有以下快速代碼。

let resolution = [imageView.frame.size.width, imageView.frame.size.height]

for x in 0...Int(resolution[0]) {
    for y in 0...Int(resolution[1]) {
        let coordinate = [x, y]
        //Find the colour of the pixel here
    }
}

我希望能夠找到照片中每個像素顯示的顏色。 有沒有辦法修改我放置的代碼“//在這里找到像素的顏色”,以便在常量坐標表示的坐標處打印像素的RGB值?

您可以嘗試以下方法:

var pixel : [UInt8] = [0, 0, 0, 0]
var colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(UnsafeMutablePointer(pixel), 1, 1, 8, 4, colorSpace, bitmapInfo)

希望這可以幫助!!

添加@Horray的答案,獲取顏色值,你必須再執行兩行。 只需檢查此實現,

var pixel : [UInt8] = [0, 0, 0, 0]
var colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(UnsafeMutablePointer(pixel), 1, 1, 8, 4, colorSpace, bitmapInfo)

// Translate the context your required point(x,y)
CGContextTranslateCTM(context, -x, -y);
yourImageView.layer.renderInContext(context)

NSLog("pixel: %d %d %d %d", pixel[0], pixel[1], pixel[2], pixel[3]);

let redColor : Float = Float(pixel[0])/255.0
let greenColor : Float = Float(pixel[1])/255.0
let blueColor: Float = Float(pixel[2])/255.0
let colorAlpha: Float = Float(pixel[3])/255.0

// Create UIColor Object    
var color : UIColor! = UIColor(red: CGFloat(redColor), green: CGFloat(greenColor), blue: CGFloat(blueColor), alpha: CGFloat(colorAlpha))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM