[swift] UIImage NSImage PNG透明区域填充自定义颜色实现

前端之家收集整理的这篇文章主要介绍了[swift] UIImage NSImage PNG透明区域填充自定义颜色实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用场合:魔方旋转控制按钮https://github.com/zephyrluo/magic

extension UIImage {
    public func maskWithColor(color: UIColor) -> UIImage {
        
        UIGraphicsBeginImageContextWithOptions(self.size,false,self.scale)
        let context = UIGraphicsGetCurrentContext()!
        
        let rect = CGRect(origin: CGPoint.zero,size: size)
        
        color.setFill()
        
        context.fill(rect)
        context.setBlendMode(.copy)
        self.draw(in: rect)
        
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return resultImage
    }
}

extension NSImage {
    convenience init(color: NSColor,img: NSImage,size: NSSize) {
        self.init(size: size)
        lockFocus()
        color.drawSwatch(in: NSRect(origin: .zero,size: size))
        img.draw(in: NSRect(origin: .zero,size: size),from: NSRect(origin: .zero,size: img.size),operation: NSCompositeSourceOver,fraction: 1)
        unlockFocus()
    }
}
原文链接:/swift/321170.html

猜你在找的Swift相关文章