Optimization Opportunity: Use a container layer instead of mask with background color

Hello,

At RunTime I'm being suggested an Optimization Opportunity for some code I've written.

The layer is using a simple layer with background color set as a mask. Instead, use a container layer of the same "frame" and "cornerRadius" as the mask, but with "masksToBounds" set to YES

I'm afraid I don't know what is meant here by a "container layer". This is the code that threw up the optimization opportunity

     let maskView = UIView(frame: CGRect(x: 0, y: 0, width: 45, height: 90))
    maskView.backgroundColor = .black
    filledImage.mask = maskView

The code above masks half of a 90x90 UIImageView filledImage. Any ideas how this could be refactoring to use a "container layer".

Many thanks

Replies

That means instead of using a mask, just use a superlayer or superview to do your clipping instead. So instead of creating a mask view and setting it as a mask on the other view, just add the other view as a subview.

  • Sorry I'm still struggling to wrap my head around this. Would you possibly be able to give a code example?

    I'm also using autolayout to position my views so I don't know if that adds any complexity. Here is the entire function, essentially I have an empty and a filled image and I want the mask to only show the left-half of the filled image.

       private func setupViews() {     let image = UIImageView()     let filledImage = UIImageView()     image.image = UIImage(named: "empty")     filledImage.image = UIImage(named: "filled")     view.addSubview(image)     view.addSubview(filledImage)     image.translatesAutoresizingMaskIntoConstraints = false     filledImage.translatesAutoresizingMaskIntoConstraints = false     image.widthAnchor.constraint(equalToConstant: 90).isActive = true     image.heightAnchor.constraint(equalToConstant: 90).isActive = true     image.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true     image.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true     filledImage.widthAnchor.constraint(equalToConstant: 90).isActive = true     filledImage.heightAnchor.constraint(equalToConstant: 90).isActive = true     filledImage.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true     filledImage.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true     let maskView = UIView(frame: CGRect(x: 0, y: 0, width: 45, height: 90))     maskView.backgroundColor = .black     filledImage.mask = maskView   }

    Many thanks, I don't know how much of an optimisation this makes but its probably not insignificant given that a Run Time warning was created for it.

Add a Comment