Swift - 获取图片UIImage指定像素的颜色值
作者:hangge | 2019-03-11 08:10
1,对 UIImage 进行扩展
为方便使用,我们首先对 UIImage 下标进行扩展,可以根据 xy 坐标值来返回指定像素的颜色(UIColor)。
import UIKit extension UIImage{ /** 根据坐标获取图片中的像素颜色值 */ subscript (x: Int, y: Int) -> UIColor? { if x < 0 || x > Int(size.width) || y < 0 || y > Int(size.height) { return nil } let provider = self.cgImage!.dataProvider let providerData = provider!.data let data = CFDataGetBytePtr(providerData) let numberOfComponents = 4 let pixelData = ((Int(size.width) * y) + x) * numberOfComponents let r = CGFloat(data![pixelData]) / 255.0 let g = CGFloat(data![pixelData + 1]) / 255.0 let b = CGFloat(data![pixelData + 2]) / 255.0 let a = CGFloat(data![pixelData + 3]) / 255.0 return UIColor(red: r, green: g, blue: b, alpha: a) } }
2,使用样例
(1)假设我们有如下一张图片:
![](http://hangge.com/blog_uploads/201902/2019021511135932031.png)
(2)下面获取这张图片上指定位置的像素颜色:
为便于观察,这里我们将获取到的 UIColor 转成十六进制颜色字符串后再打印出来。其具体转换方法,可以参考我之前的这篇文章:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 获取图片 let image = UIImage(named: "img")! let width = Int(image.size.width) let height = Int(image.size.height) print("图片尺寸:", "\(width) * \(height)") // 获取指定像素颜色 if let hexString = image[0, 0]?.hexString { print("左上角颜色:", hexString) } if let hexString = image[width, 0]?.hexString { print("右上角颜色:", hexString) } if let hexString = image[width/2, height/2]?.hexString { print("中间点颜色:", hexString) } } }
(3)运行结果如下:
![](http://hangge.com/blog_uploads/201902/201902151119439640.png)
全部评论(0)