在app開(kāi)發(fā)中定踱,經(jīng)常會(huì)給一些view加上漸變色碌更,下面我寫(xiě)一下我在項(xiàng)目中的實(shí)現(xiàn)方法。
漸變色尊剔,其實(shí)就是一種顏色爪幻,所以就是UIColor的一種。因此我們可以給UIColor寫(xiě)一個(gè)分類须误,在需要用的地方直接使用類方法挨稿,得到我們想要的漸變色。
首先京痢,我們創(chuàng)建一個(gè)UIColor的分類UIColor+Gradient奶甘,然后在.h文件中定義一個(gè)枚舉,用來(lái)設(shè)置漸變的方向:
typedefNS_ENUM(NSInteger, ZQGradientChangeDirection) {
? ? ZQGradientChangeDirectionLevel, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //水平方向漸變 ?
? ? ZQGradientChangeDirectionVertical, ? ? ? ? ? ? ? ? ? ? ? ? ? //垂直方向漸變
? ? ZQGradientChangeDirectionUpwardDiagonalLine, ? ?//主對(duì)角線方向漸變
? ? ZQGradientChangeDirectionDownDiagonalLine, ? ? ??//副對(duì)角線方向漸變
};
接著定義一個(gè)類初始化方法:
/*
? ? ? ? ? size:漸變區(qū)域的尺寸
? direction:漸變方向
?startColor:開(kāi)始顏色
?? endColor:結(jié)束顏色
?*/
+ (instancetype)bm_colorGradientChangeWithSize:(CGSize)size
?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? direction:(IHGradientChangeDirection)direction
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? startColor:(UIColor*)startcolor
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? endColor:(UIColor*)endColor;
好了祭椰,現(xiàn)在去.m文件中實(shí)現(xiàn)就可以了臭家,直接上代碼:
+ (instancetype)bm_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);
? ? CGPointstartPoint =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=@[(__bridgeid)startcolor.CGColor, (__bridgeid)endColor.CGColor];
? ? UIGraphicsBeginImageContext(size);
? ? [gradientLayerrenderInContext:UIGraphicsGetCurrentContext()];
? ? UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
? ? UIGraphicsEndImageContext();
? ? return [UIColor colorWithPatternImage:image];
}
好了疲陕,可以使用了,這是各個(gè)方向的效果圖:
ZQGradientChangeDirectionLevel:
ZQGradientChangeDirectionVertical:
ZQGradientChangeDirectionUpwardDiagonalLine:
ZQGradientChangeDirectionDownDiagonalLine: