将方形 UIImage 转换为圆形 UIIMage 以便与 CAEmitterCell.contents 一起使用

Convert Square UIImage to round UIIMage for use with CAEmitterCell.contents

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

我正在使用我在 Whosebug 上找到的以下 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
    }
}

我的图片本来是白底的,但是图片的重要部分也有白色。我暂时把背景改成黑色,拍了一张快照,然后把黑色转成透明,再把背景改回白色。

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