我用户一个计时器射击每0.1秒的功能重复使用UIGraphicsGetImageFromCurrentImageContext得到一个UIImage并分配到一个@IBOutllet弱UImageView.image。(coverImageView)的iOS内存警告
var timer:Timer?
func fireTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { [weak self] _ in
self?.lightTheFier()
})
}
func invalidateTimer() {
timer?.invalidate()
timer = nil
}
func lightTheFier() {
var points = [CGPoint]()
for pin in pins {
let point = mapView.convert(pin.coordinate, toPointTo: coverImageView)
points.append(point)
}
coverImageView.image = getMaskedImage(points: points, zoomLevel: Int(mapView.zoomLevel()))
}
func getOringinalImageFromPath() -> UIImage{
UIGraphicsBeginImageContextWithOptions(coverImageView.bounds.size, false, 0.0)
let path = UIBezierPath(rect: coverImageView.bounds)
UIColor.black.setFill()
path.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func getMaskImageFromPath(points:[CGPoint], scale:CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(coverImageView.bounds.size, false, 0.0)
let radius:CGFloat = 10.0
UIColor.blue.setFill()
for point in points {
let rect = CGRect(x: point.x - (scale*radius/2), y: point.y - (scale*radius/2), width: scale*radius, height: scale*radius)
let path = UIBezierPath(ovalIn: rect)
path.fill()
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func getMaskedImage(points:[CGPoint], zoomLevel:Int) -> UIImage{
let orImage = getOringinalImageFromPath().cgImage
let maskImage = getMaskImageFromPath(points: points, scale: CGFloat(zoomLevel)).cgImage
let mask = CGImage(maskWidth: maskImage!.width, height: maskImage!.height, bitsPerComponent: maskImage!.bitsPerComponent, bitsPerPixel: maskImage!.bitsPerPixel, bytesPerRow: maskImage!.bytesPerRow, provider: maskImage!.dataProvider!, decode: nil, shouldInterpolate: true)
let maskRef = orImage?.masking(mask!)
let image = UIImage(cgImage: maskRef!)
return image
}
所有代码以上是在ViewController.swift中进行测试。
在函数运行过程中,内存越来越大,我想要的是当我使计时器无效时,它可以释放内存。
我该如何解决这个问题?
放,你必须尝试 –
我已编辑它的代码,谢谢! –
在ARC中,某些变量被释放,所有使用该变量的变量都需要超出范围。看看'coverImageView'将会超出范围。更好的方法是在需要时请求图像,而不是使用定时器。因此,当图像需要显示时,检查图像是否已经可用,否则获取它。 – user1046037