0

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

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

我正在获取结果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)
  }
}
4

1 回答 1

0

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

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

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
    }
}

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

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

于 2018-06-27T20:26:19.087 回答