gpt4 book ai didi

Swift:UIGraphicsImageRendererFormat 而不是 UIGraphicsBeginImageContext 返回空白图像

转载 作者:行者123 更新时间:2023-11-28 05:57:57 30 4
gpt4 key购买 nike

我正在用 UIGraphicsImageRendererFormat 替换 UIGraphicsBeginImageContext 以优化性能并使我的代码现代化。出于某种原因,UIGraphicsImageRendererFormat 在我的函数中返回了一个空白图像。我一定是做错了什么!

旧功能:(工作正常)

func drawImageInRect(inputImage: UIImage, inRect imageRect: CGRect) -> UIImage {

UIGraphicsBeginImageContext(self.size)
self.draw(in:(CGRect(x:0.0, y:0.0, width:self.size.width, height:self.size.height)))
inputImage.draw(in:(imageRect))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}

新功能:(不画任何东西)

func drawImageInRect(inputImage: UIImage, inRect imageRect: CGRect) -> UIImage {


let renderFormat = UIGraphicsImageRendererFormat.default()
renderFormat.opaque = true
let renderer = UIGraphicsImageRenderer(size: self.size, format: renderFormat)

let scaledImage = renderer.image {
(context) in
inputImage.draw(in: imageRect)
}
return scaledImage
}

最佳答案

问题是在你更新的函数中你忘记绘制 self 所以你得到了一个黑色背景,而原来的图像应该是。

func drawImageInRect(inputImage: UIImage, inRect imageRect: CGRect) -> UIImage {
let renderFormat = UIGraphicsImageRendererFormat.default()
renderFormat.opaque = true
let renderer = UIGraphicsImageRenderer(size: self.size, format: renderFormat)

let scaledImage = renderer.image {
(context) in
// Add the following missing line
self.draw(in:(CGRect(x:0.0, y:0.0, width:self.size.width, height:self.size.height)))
inputImage.draw(in: imageRect)
}
return scaledImage
}

关于Swift:UIGraphicsImageRendererFormat 而不是 UIGraphicsBeginImageContext 返回空白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50846564/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com