iosswiftimage-masking

Swift 4 correctly remove mask


I have a scrollview containing multiple UIImageViews that are kept in an array. Each of these UIImageViews has the same background image, but a unique mask. When these images are not displayed on the screen, I want to remove the mask to save memory. A function like the following is called when the mask has to be created or deleted. In this case however, the memory footprint will not decrease when the imageView mask is set to nil.

func updateView(imageName: String, imageView: UIImageView, show: Bool)
    if show {
       let newMask = UIImageView()
       newMask.image = UIImage(named: imageName)
       newMask.frame = frame
       imageView.mask = newMask
    } else {
       imageView.mask = nil
    }
 }

How to solve this problem? As a beginner I've been looking for the answer for days and any help would be very much appreciated.


Solution

  • The largest object in your code is the UIImage that you are using as the image of the UIImageView that you are using as a mask. (The UIImageView itself is negligible.) UIImages loaded by saying UIImage(named:) are cached; therefore, removing the UIImageView doesn't cause memory to decrease. But the good news is that the next time you do this, the image is already cached, so memory won't increase either.

    Note too that if the UIImage is large, its memory will be large, even if you are displaying it small (i.e. if you are making the UIImageView do the work of reducing the UIImage size to its own size). That is a huge waste of memory. There are standard techniques for loading or redrawing a UIImage at the actual size needed for display, which can save massively on memory.