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

标签 ios swift uiimage transparency caemittercell

我有一个自定义 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
    }
}

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

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

关于ios - 将方形 UIImage 转换为圆形 UIIMage 以与 CAEmitterCell.contents 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51070186/

相关文章:

swift - 从 UIWebView 创建 PDF

cocoa - 当警报 View 关闭时,右侧导航栏按钮会移动

ios - CMAltitudeData 最后有一些奇怪的数据,有什么想法吗?

ios - 在 xcode beta 中运行 unity arkit 项目时出现语义问题

使用CombineLatest 与可选发布者进行 Swift 组合

ios - URLRequest POST 在 Swift 5 中不起作用。服务器可能有问题?

ios - 为什么 `pod install`会改变PODS_ROOT路径?

ios - Xamarin 错误代码 34018

ios - 在 ImageContext 中创建 UIImage 的自动释放

iOS - UIImageView - 如何处理 UIImage 图像方向