为什么更改Uiimage颜色时App崩溃了

时间:2019-06-16 23:40:12

标签: swift uiimage

我更改了Uiimage的颜色,但应用程序崩溃了。我循环执行此代码。我添加了Autoreleasepool,但没有解决我的问题。

func withColor(_ color: UIColor) -> UIImage {
    //this method is extendtion of UIImage
    UIGraphicsBeginImageContextWithOptions(size, false, scale)
    guard let ctx = UIGraphicsGetCurrentContext(), let cgImage = cgImage else { return self }
    color.setFill()
    ctx.translateBy(x: 0, y: size.height)
    ctx.scaleBy(x: 1.0, y: -1.0)
    ctx.clip(to: CGRect(x: 0, y: 0, width: size.width, height: size.height), mask: cgImage)
    ctx.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
    guard let colored = UIGraphicsGetImageFromCurrentImageContext() else { return self }
    UIGraphicsEndImageContext()
    return colored
}
 func getImage() {
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
    for i in 0..<50{
        let url = arrImages[i]
        let elemetView = UIImageView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))

        elementView.imgVContent.image = UIImage(named: url)
        if let imgColor = elementData.bgColor, imgColor != ""{
            elementView.image = elementView.image?.withColor(UIColor(hexString: imgColor))
            elementView.image.imgColor = UIColor(hexString: imgColor)
        }

        view.addSubview(elementView)
    }
}

1 个答案:

答案 0 :(得分:0)

您提到您已经使用了自动释放池,但是我找不到它。可能尝试按以下方式使用,看看是否可以解决问题。

在您的getImage函数中,将如下所示的for循环与autoreleasepool一起使用。

for i in 0..<50{

    autoreleasepool{
            let url = arrImages[i]
            let elemetView = UIImageView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))

            elementView.imgVContent.image = UIImage(named: url)
            if let imgColor = elementData.bgColor, imgColor != ""{
                elementView.image = elementView.image?.withColor(UIColor(hexString: imgColor))
                elementView.image.imgColor = UIColor(hexString: imgColor)
            }

            view.addSubview(elementView)
        }
    }