swift 獲取圖像指定點的顏色(UIColor)

在 iOS 開發中,有時候須要獲取圖像中某個像素點的顏色,返回 UIColor 值。

網上收集資料,參考各類方案,最後總結以下:swift

/// 獲取圖片觸摸點顏色
///
/// 參考資料
/// https://blog.csdn.net/huangfei711/article/details/76189655
/// - Parameters:
/// - image: 要獲取顏色的圖片
/// - point: 觸摸點
/// - Returns: 獲取到的顏色
func cxg_getPointColor(withImage image: UIImage, point: CGPoint) -> UIColor? {

    guard CGRect(origin: CGPoint(x: 0, y: 0), size: image.size).contains(point) else {
        return nil
    }

    let pointX = trunc(point.x);
    let pointY = trunc(point.y);

    let width = image.size.width;
    let height = image.size.height;
    let colorSpace = CGColorSpaceCreateDeviceRGB();
    var pixelData: [UInt8] = [0, 0, 0, 0]

    pixelData.withUnsafeMutableBytes { pointer in
        if let context = CGContext(data: pointer.baseAddress, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue), let cgImage = image.cgImage {
            context.setBlendMode(.copy)
            context.translateBy(x: -pointX, y: pointY - height)
            context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        }
    }

    let red = CGFloat(pixelData[0]) / CGFloat(255.0)
    let green = CGFloat(pixelData[1]) / CGFloat(255.0)
    let blue = CGFloat(pixelData[2]) / CGFloat(255.0)
    let alpha = CGFloat(pixelData[3]) / CGFloat(255.0)

    if #available(iOS 10.0, *) {
        return UIColor(displayP3Red: red, green: green, blue: blue, alpha: alpha)
    } else {
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
}
複製代碼

更多知識請移步:CuiXgの博客ui

相關文章
相關標籤/搜索