Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add shade gradient to the bottom of a uitableviewcell / uiimageview

Does anyone know how add a gradient to the bottom of a uitableviewcell or the uiimageview like the image shown below does?

enter image description here

like image 609
SleepsOnNewspapers Avatar asked May 14 '15 22:05

SleepsOnNewspapers


1 Answers

Add this class into your project (swift):

class UIGradientImageView: UIImageView {

let myGradientLayer: CAGradientLayer

 override init?(frame: CGRect){
    myGradientLayer = CAGradientLayer()
    super.init(frame: frame)
    self.setup()
    addGradientLayer()
 }

 func addGradientLayer(){
    if myGradientLayer.superlayer == nil{
        self.layer.addSublayer(myGradientLayer)
    }
 }

 required init(coder aDecoder: NSCoder){
    myGradientLayer = CAGradientLayer()
    super.init(coder: aDecoder)
    self.setup()
    addGradientLayer()
 }

 func getColors() -> [CGColorRef] {
    return [UIColor.clearColor().CGColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).CGColor]
 }

 func getLocations() -> [CGFloat]{
    return [0.5,  0.9]
 }

 func setup() {
     myGradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
     myGradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
    
     let colors = getColors()
     myGradientLayer.colors = colors
     myGradientLayer.opaque = false
     myGradientLayer.locations = getLocations()
 }

 override func layoutSubviews() {
    super.layoutSubviews()
    myGradientLayer.frame = self.layer.bounds
 }
}

UPDATE: Objective-C translated solution. Credits to @SleepsOnNewspapers.

 #import "UIGradientImageView.h"

 @interface UIGradientImageView()

  @property (nonatomic, strong) CAGradientLayer *myGradientLayer;

 @end

 @implementation UIGradientImageView

 -(instancetype)initWithFrame:(CGRect)frame{

 if(self){
  self = [super initWithFrame:frame];
  self.myGradientLayer = [[CAGradientLayer alloc]init];
  [self setup];
  [self addGradientLayer];
  }
 return self;
 }

 -(instancetype)initWithCoder:(NSCoder *)aDecoder{

 if(self){
   self = [super initWithCoder:aDecoder];
   self.myGradientLayer = [[CAGradientLayer alloc]init];
   [self setup];
   [self addGradientLayer];
  }
  return self;
 }

 -(void)addGradientLayer{
 if (self.myGradientLayer.superlayer == nil) {
  [self.layer addSublayer:self.myGradientLayer];
 }
}

Make your UIImageView class on your storyboard to be this one instead of default.

enter image description here

like image 194
Hugo Alonso Avatar answered Sep 19 '22 02:09

Hugo Alonso