Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS fade to black at top of UIImageView

I have a UITableView where my cell backgroundView is a UIImageView. I would like top of each image to fade to black so I can overlay some white text.

I have looked at some answers like this, but none seem to be working.

In tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) I have tried:

var imageView = UIImageView(image: image)

var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = imageView.frame
gradient.colors = [UIColor.blackColor(), UIColor.clearColor()]
gradient.locations = [0.0, 0.1]
imageView.layer.insertSublayer(gradient, atIndex: 0)

cell!.backgroundView = imageView

But I see no gradient and no difference from when I remove the gradient code. Is my gradient sitting under the image?

If I replace the line imageView.layer.insertSublayer(gradient, atIndex: 0) with imageView.layer.mask = gradient then my cells are just blank and white (no image anymore).

like image 423
Imran Avatar asked Aug 06 '15 15:08

Imran


3 Answers

In your gradient.colors you need to have array of CGColor, so:

gradient.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor]
like image 83
libec Avatar answered Oct 17 '22 06:10

libec


I forget how the layers array is ordered. However, you should just add your gradient layer on top of your image view's layer using addSubLayer, not insertSublayer:atIndex: You want the gradient layer on top of the other layer so that it's non-opaque parts cover the image view.

like image 31
Duncan C Avatar answered Oct 17 '22 07:10

Duncan C


For Swift 3.0, some slight tweaks required:

    let gradient: CAGradientLayer = CAGradientLayer()
    gradient.frame = imageView.frame
    gradient.colors = [UIColor.black.cgColor, UIColor.clear.cgColor]
    gradient.locations = [0.0, 0.1]
    imageView.layer.insertSublayer(gradient, at: 0)
like image 3
David West Avatar answered Oct 17 '22 06:10

David West