将 Square UIImage 转换为圆形 UIIMage,以便与 CAEmitterCell.content 一起



我有一个自定义 UI 组件,它生成一个圆球的图像,上面叠加了一些标签。

我正在使用我在StackOverflow上找到的以下UIView扩展来拍摄组件的快照。

我正在获取生成的UIImage并在CAEmitterCell中使用它.

我的问题是快照图像是方形的 - 我的圆球在白色背景上。 我希望背景在发出时清晰,但我似乎找不到一种方法来做到这一点。

有什么方法可以修改UIImage使其角透明吗?

谢谢。

extension UIView {
/// Create snapshot
///
/// - parameter rect: The `CGRect` of the portion of the view to return. If `nil` (or omitted),
///                   return snapshot of the whole view.
///
/// - returns: Returns `UIImage` of the specified portion of the view.
func snapshot(of rect: CGRect? = nil) -> UIImage? {
// snapshot entire view
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let wholeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// if no `rect` provided, return image of whole view
guard let image = wholeImage, let rect = rect else { return wholeImage }
// otherwise, grab specified `rect` of image
let scale = image.scale
let scaledRect = CGRect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale)
guard let cgImage = image.cgImage?.cropping(to: scaledRect) else { return nil }
return UIImage(cgImage: cgImage, scale: scale, orientation: .up)
}
}

在弄清楚如何在这里表达我的问题之后,我想到了另一种方法来搜索我的答案并找到了解决方案。

有人发布了一个扩展程序,将白色背景变为透明,作为对上一个问题的答案。 白色对我不起作用,但简单的编辑和名称更改使扩展适用于黑色背景而不是白色。

extension UIImage {
func imageByMakingBlackBackgroundTransparent() -> UIImage? {
let image = UIImage(data: UIImageJPEGRepresentation(self, 1.0)!)!
let rawImageRef: CGImage = image.cgImage!
let colorMasking: [CGFloat] = [0, 0, 0, 0, 0, 0]
UIGraphicsBeginImageContext(image.size);
let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
let result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result
}
}

我的图像最初是白色背景,但在图像的重要部分也有白色。 我暂时将背景更改为黑色,拍摄了快照,然后将黑色转换为透明,然后将背景更改回白色。

最终结果是我的问题已解决。 感谢任何花时间阅读或思考这个问题的人。

最新更新