1

I'm trying to add opacity to my view. When I add a CAGradientlayer, I roughly get, what I planned, but have a few issues.

  1. I can't change the color. No matter what values I use, I'll always get a white layer
  2. Even though I wanted it to be distributed over the whole view, it seems like it has an offset to the left.

enter image description here

My code is as follows:

let maskLayer = CAGradientLayer()
    
maskLayer.anchorPoint = CGPoint(x: 0.0, y: 0.0)
    
maskLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
maskLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
    
maskLayer.colors = [UIColor(white: 0.0, alpha: 0.0).CGColor, UIColor(white: 1.0, alpha: 1.0).CGColor, UIColor(white: 0.0, alpha: 0.0).CGColor]
maskLayer.locations = [0.0, 0.5, 1.0]
maskLayer.bounds = CGRectMake(0, 0, self.frame.width, self.frame.height)
    
self.layer.mask = maskLayer

What am I doing wrong?

Thanks

Community
  • 1
  • 1
Jan
  • 1,827
  • 2
  • 16
  • 29

1 Answers1

0

About the white, this is because a layer mask does not contribute to color, only transparency. Essentially, only the alpha component has an effect, and the R,G,B components of the layer mask are ignored.

About the offset, could it be because your view is getting resized, and your layer isn't kept up to date? If so you could see the answer to this other question: CALayers didn't get resized on its UIView's bounds change. Why?

Community
  • 1
  • 1
Clafou
  • 15,250
  • 7
  • 58
  • 89
  • Thanks for the clearification. When I apply layoutSubviews as suggested in your link, it clears an offset to the left and adds one instead to the bottom. – Jan Nov 09 '14 at 12:46
  • override func layoutSubviews() { lineLayer.frame = self.bounds super.layoutSubviews() } where lineLayer is a calayer that is added as a subview – Jan Nov 09 '14 at 12:58
  • Since I've been to slow to edit my comment: though this might not be the error of the cagradientlayer. The error is better described at: http://stackoverflow.com/questions/26828134/uibezierpath-moved-half-aside – Jan Nov 09 '14 at 13:04
  • okay the offset to y was cause I've had a wrong underständing of uibezierpath. – Jan Nov 09 '14 at 13:12