渐变色需求:(因为UIButton, UILabel, UITextField等均为UIView子视图,因此以下方法均可行)
-
(void)changeColors:(UIView *)myView{
CAGradientLayer *_gradLayer = [CAGradientLayer layer];
NSArray *colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithWhite:0 alpha:1] CGColor],
(id)[[UIColor colorWithWhite:0 alpha:0.8] CGColor],
(id)[[UIColor colorWithWhite:0 alpha:0.6] CGColor],
nil];
[_gradLayer setColors:colors];
//渐变起止点,point表示向量
[_gradLayer setStartPoint:CGPointMake(1.0f, 0.0f)];
[_gradLayer setEndPoint:CGPointMake(0.0f, 0.0f)];
[_gradLayer setFrame:myView.bounds];
[myView.layer setMask:_gradLayer];
}
//设置导航栏渐变色
typedef NS_ENUM(NSInteger, IHGradientChangeDirection) {
IHGradientChangeDirectionLevel,
IHGradientChangeDirectionVertical,
IHGradientChangeDirectionUpwardDiagonalLine,
IHGradientChangeDirectionDownDiagonalLine,
};
-
(UIColor *)saj_colorGradientChangeWithSize:(CGSize)size
direction:(IHGradientChangeDirection)direction
startColor:(UIColor *)startcolor
endColor:(UIColor *)endColor {if (CGSizeEqualToSize(size, CGSizeZero) || !startcolor || !endColor) {
return nil;
}CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = CGRectMake(0, 0, size.width, size.height);CGPoint startPoint = CGPointZero;
if (direction == IHGradientChangeDirectionDownDiagonalLine) {
startPoint = CGPointMake(0.0, 1.0);
}
gradientLayer.startPoint = startPoint;CGPoint endPoint = CGPointZero;
switch (direction) {
case IHGradientChangeDirectionLevel:
endPoint = CGPointMake(1.0, 0.0);
break;
case IHGradientChangeDirectionVertical:
endPoint = CGPointMake(0.0, 1.0);
break;
case IHGradientChangeDirectionUpwardDiagonalLine:
endPoint = CGPointMake(1.0, 1.0);
break;
case IHGradientChangeDirectionDownDiagonalLine:
endPoint = CGPointMake(1.0, 0.0);
break;
default:
break;
}
gradientLayer.endPoint = endPoint;gradientLayer.colors = @[(__bridge id)startcolor.CGColor, (__bridge id)endColor.CGColor];
UIGraphicsBeginImageContext(size);
[gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [UIColor colorWithPatternImage:image];
}