[英]iOS memory warning in Swift
我使用一個計時器,每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中進行測試。
函數運行期間內存增加是很好的,我想要的是當我使計時器無效時可以釋放內存。
我應該如何解決此問題?
您正在啟動一個圖像上下文: 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!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.