ios – 在uitableviewcell / uiimageview的底部添加阴影渐变

前端之家收集整理的这篇文章主要介绍了ios – 在uitableviewcell / uiimageview的底部添加阴影渐变前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有谁知道如何在uitableviewcell或uiimageview的底部添加渐变,如下图所示?

解决方法

将此类添加到项目中( 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
 }
}

更新:Objective-C翻译解决方案.积分@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];
 }
}

将故事板上的UIImageView类设为此类而不是默认类.

原文链接:https://www.f2er.com/iOS/327825.html

猜你在找的iOS相关文章