我使用定时器每0.1秒触发一次函数重复以使用UIGraphicsGetImageFromCurrentImageContext获取UIImage并分配给@IBOutllet弱UImageView.image。(coverImageView)
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中进行测试。
在函数运行期间内存增加很好,我想要的是它可以在我使计时器无效时释放内存。
我该如何解决此问题?
答案 0 :(得分:0)
你正在开始一个图像上下文:UIGraphicsBeginImageContextWithOptions
,但你永远不会结束它。您需要在UIGraphicsEndImageContext()
和getMaskImageFromPath
方法中添加getOringinalImageFromPath
:
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() // Missing this line
return image!
}