标签:
UIView颜色渐变,可以直接使用CAGradientLayer或者重写drawRect:都可以实现渐变的效果,其中本质都是一样的.
比较简单的渐变只要设置过渡的颜色,和开始的位置,若不设置位置,会默认平均分.
1.使用 CAGradientLayer
//gradientLayer
1 //gradientLayer 2 func addGradientViewLayer(){ 3 let contentView = UIView(frame: CGRectMake(100, 100, 100, 100)) 4 contentView.backgroundColor = UIColor.greenColor() 5 self.view.addSubview(contentView) 6 7 //create gradientLayer 8 let gradientLayer : CAGradientLayer = CAGradientLayer() 9 gradientLayer.frame = CGRectMake(0, 20, 100, 40); 10 //gradient colors 11 let colors = [UIColor.redColor().CGColor,UIColor.blackColor().CGColor] 12 13 let locations = [0.0,1.0] 14 gradientLayer.colors = colors 15 gradientLayer.locations = locations 16 contentView.layer.insertSublayer(gradientLayer, atIndex: 0) 17 18 }
效果图,绿色背景View上的红黑渐变
2.drawRect:自定义
1 override func drawRect(rect: CGRect) { 2 let colorSpace = CGColorSpaceCreateDeviceRGB() 3 let context = UIGraphicsGetCurrentContext() 4 let gradientStartColor = UIColor.greenColor() 5 6 let gradientEndColor = UIColor.redColor() 7 //colors 8 let gradientColors : CFArray = [gradientStartColor.CGColor,gradientEndColor.CGColor] 9 10 //locations 11 let gradientLocations : [CGFloat] = [0.0,1.0] 12 let gradient = CGGradientCreateWithColors(colorSpace, gradientColors, gradientLocations) 13 14 let pathRect = CGRectInset(self.bounds, 20, 20) 15 16 let topPoint = CGPointMake(self.bounds.size.height/2, 20) 17 let bottomPoint = CGPointMake(self.bounds.size.width/2, self.bounds.size.height - 20) 18 19 let roundedRectanglePath = UIBezierPath(roundedRect: pathRect, cornerRadius: 4) 20 CGContextSaveGState(context) 21 roundedRectanglePath.addClip() 22 CGContextDrawLinearGradient(context, gradient, bottomPoint, topPoint, 0) 23 CGContextRestoreGState(context) 24 25 }
效果,红绿渐变
标签:
原文地址:http://www.cnblogs.com/luohome-ios/p/4976569.html