如何将UIImageView渲染为UIImage

时间:2018-09-14 14:33:38

标签: ios swift uiview uiimageview uiimage

我创建了一个UIImageView BackView ,以创建一个模糊的背景,其中渐变图层为黑色。 (要创建类似Spotify的艺术家个人资料。)

我想将此图像视图放置在NavigationBar后面,以获得更好的外观。但是要实现这一点,我需要一个UIImage。我不能仅使用BackView.image,因为这只是没有BlurryView或渐变图层的源图像。

所以我在HackingWithSwift上找到了这段代码:

let renderer = UIGraphicsImageRenderer(size: rect.size)
let image = renderer.image { ctx in
    backView.drawHierarchy(in: backView.bounds, afterScreenUpdates: true)
}

但是,这并不像令人遗憾的那样呈现视图。它仅绘制了渐变图层,后面没有任何内容。有人有代码片段将所有子视图都放入渲染的图像中吗?

下面,我添加了UIImageView类和处理渲染器的函数:

class BackView: UIImageView {

var thisframe: CGRect
var anImage: UIImage? {
    didSet {
        setupImage()
    }
}

override init(frame: CGRect) {
    self.thisframe = frame
    super.init(frame: .zero)
    self.anImage = UIImage(named: "gray")
    setupImage()
}

func setupImage() {
    self.image = anImage
    self.addSubview(blurry)
    self.addSubview(blacky)
    gradientLayer.removeFromSuperlayer()
    self.layer.insertSublayer(gradientLayer, at: 1)
    print(gradientLayer.bounds)
}

lazy var blurry: UIVisualEffectView = {
    let blur = UIVisualEffectView()
    blur.effect = UIBlurEffect(style: .regular)
    blur.frame = (thisframe)
    return blur
}()

lazy var blacky: UIImageView = {
    let black = UIImageView()
    black.backgroundColor = .black
    black.alpha = 0.0
    black.frame = (thisframe)
    return black
}()

lazy var gradientLayer: CAGradientLayer = {
    let gradient = CAGradientLayer()
    gradient.colors = [UIColor.black.withAlphaComponent(0.0).cgColor,
                       UIColor.black.withAlphaComponent(1.0).cgColor]
    gradient.frame = (thisframe)
    gradient.startPoint = CGPoint(x: 0.5, y: 0)
    gradient.endPoint = CGPoint(x: 0.5, y: 1)
    return gradient
}()

这里是函数:

    func setupNavBarBackground() {
    let renderer = UIGraphicsImageRenderer(size: rect.size)
    let image = renderer.image { ctx in
        backView.drawHierarchy(in: backView.bounds, afterScreenUpdates: true)
    }
    self.navigationController?.navigationBar.barTintColor = .clear
    self.navigationController?.navigationBar.backgroundColor = .clear
    self.navigationController?.navigationBar.setBackgroundImage(image, for: .default)
    self.navigationController?.navigationBar.shadowImage = image
}

0 个答案:

没有答案