如何在Swift中查找UIImage中单个像素的颜色

4
我有如下的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
    }
}

我希望能够找到照片中每个像素所显示的颜色。是否有一种方法可以修改代码,在我放置“//Find the colour of the pixel here”处,以便打印出由常数坐标表示的坐标处像素的RGB值?


请参考以下答案:https://dev59.com/b3A75IYBdhLWcg3wdIz7 - Rizwan Shaikh
2个回答

3

除了@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))

你可以通过直接访问像素点 x, y 来节省性能,而不是先绘制它。 - Sash Zats

2
您可以尝试以下方法:
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)

希望这有所帮助!!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接