在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 对【UIImage】进行扩展 1 import UIKit 2 3 extension UIImage{ 4 5 /** 6 根据坐标获取图片中的像素颜色值 7 */ 8 subscript (x: Int, y: Int) -> UIColor? { 9 10 if x < 0 || x > Int(size.width) || y < 0 || y > Int(size.height) { 11 return nil 12 } 13 14 let provider = self.cgImage!.dataProvider 15 let providerData = provider!.data 16 let data = CFDataGetBytePtr(providerData) 17 18 let numberOfComponents = 4 19 let pixelData = ((Int(size.width) * y) + x) * numberOfComponents 20 21 let r = CGFloat(data![pixelData]) / 255.0 22 let g = CGFloat(data![pixelData + 1]) / 255.0 23 let b = CGFloat(data![pixelData + 2]) / 255.0 24 let a = CGFloat(data![pixelData + 3]) / 255.0 25 26 return UIColor(red: r, green: g, blue: b, alpha: a) 27 } 28 } 对【UIColor】进行扩展 1 import UIKit 2 3 extension UIColor { 4 5 // Hex String -> UIColor 6 convenience init(hexString: String) { 7 let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines) 8 let scanner = Scanner(string: hexString) 9 10 if hexString.hasPrefix("#") { 11 scanner.scanLocation = 1 12 } 13 14 var color: UInt32 = 0 15 scanner.scanHexInt32(&color) 16 17 let mask = 0x000000FF 18 let r = Int(color >> 16) & mask 19 let g = Int(color >> 8) & mask 20 let b = Int(color) & mask 21 22 let red = CGFloat(r) / 255.0 23 let green = CGFloat(g) / 255.0 24 let blue = CGFloat(b) / 255.0 25 26 self.init(red: red, green: green, blue: blue, alpha: 1) 27 } 28 29 // UIColor -> Hex String 30 var hexString: String? { 31 var red: CGFloat = 0 32 var green: CGFloat = 0 33 var blue: CGFloat = 0 34 var alpha: CGFloat = 0 35 36 let multiplier = CGFloat(255.999999) 37 38 guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { 39 return nil 40 } 41 42 if alpha == 1.0 { 43 return String( 44 format: "#%02lX%02lX%02lX", 45 Int(red * multiplier), 46 Int(green * multiplier), 47 Int(blue * multiplier) 48 ) 49 } 50 else { 51 return String( 52 format: "#%02lX%02lX%02lX%02lX", 53 Int(red * multiplier), 54 Int(green * multiplier), 55 Int(blue * multiplier), 56 Int(alpha * multiplier) 57 ) 58 } 59 } 60 } 测试示例: 1 // 获取图片 2 let image = UIImage(named: "img")! 3 let width = Int(image.size.width) 4 let height = Int(image.size.height) 5 print("图片尺寸:", "\(width) * \(height)") 6 7 // 获取指定像素颜色 8 if let hexString = image[0, 0]?.hexString { 9 print("左上角颜色:", hexString) 10 } 11 if let hexString = image[width, 0]?.hexString { 12 print("右上角颜色:", hexString) 13 } 14 if let hexString = image[width/2, height/2]?.hexString { 15 print("中间点颜色:", hexString) 16 }
|
请发表评论