我們經(jīng)常會(huì)在UIView添加漸變的背景色。雖然找一張漸變顏色的背景圖很方便,但是圖片是要占用資源的春弥,同時(shí)文件也會(huì)變大。所以苞俘,我們完全可以使用代碼來實(shí)現(xiàn)效果。
下面是使用代碼來寫漸變色的方法龄章。
1.使用CAGradientLayer實(shí)現(xiàn)漸變
CAGradientLayer是CALayer的一個(gè)特殊子類吃谣,用于生成顏色漸變的圖層,使用較為方便做裙,不過這里的顏色是添加到子圖層的岗憋,再次添加漸變,會(huì)在圖層上面添加菇用,非替換澜驮。
下面介紹下它的相關(guān)屬性:
1.colors 漸變的顏色
2.locations 漸變顏色的分割點(diǎn)
3.startPoint&endPoint 顏色漸變的方向,范圍在(0,0)與(1.0,1.0)之間惋鸥,如(0,0)(1.0,0)代表水平方向漸變,(0,0)(0,1.0)代表豎直方向漸變
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor yellowColor].CGColor, (__bridge id)[UIColor blueColor].CGColor];//這里顏色漸變
gradientLayer.locations = @[@0.3, @0.5, @1.0];//顏色位置
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1.0, 0);
gradientLayer.frame = CGRectMake(0, 100, 300, 100);漸變區(qū)域的大小杂穷,一般同view
[self.view.layer addSublayer:gradientLayer];
2.繪制UIimage漸變圖實(shí)現(xiàn)漸變,這種方法的好處在于可以直接更換背景卦绣,而不是在子圖層再添加一個(gè)耐量。
const CGFloat location[] ={0,1};
const CGFloat components[] ={
0.0,0.0,0.0,0.6,
0.0,0.0,0.0,0.0
};
UIImage *backgroundImage = [self getGradientImageWithSize:self.nBarView.frame.size locations:location components:components count:2];
_view.backgroundColor = [UIColor colorWithPatternImage:backgroundImage];
//漸變
- (UIImage *)getGradientImageWithSize:(CGSize)size
locations:(const CGFloat[])locations
components:(const CGFloat[])components
count:(NSInteger)count
{
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
//創(chuàng)建色彩空間
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
/*指定漸變色
space:顏色空間
components:顏色數(shù)組,注意由于指定了RGB顏色空間,那么四個(gè)數(shù)組元素表示一個(gè)顏色(red滤港、green廊蜒、blue趴拧、alpha),
如果有三個(gè)顏色則這個(gè)數(shù)組有4*3個(gè)元素
locations:顏色所在位置(范圍0~1)山叮,這個(gè)數(shù)組的個(gè)數(shù)不小于components中存放顏色的個(gè)數(shù)
count:漸變個(gè)數(shù)著榴,等于locations的個(gè)數(shù)
*/
CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, count);
//釋放顏色空間
CGColorSpaceRelease(colorSpace);
//這里調(diào)節(jié)漸變方向,此時(shí)的漸變是上到下
CGPoint startPoint = (CGPoint){size.width,0};
CGPoint endPoint = (CGPoint){size.width,size.height};
/*繪制線性漸變
context:圖形上下文
gradient:漸變色
startPoint:起始位置
endPoint:終止位置
options:繪制方式,kCGGradientDrawsBeforeStartLocation 開始位置之前就進(jìn)行繪制屁倔,到結(jié)束位置之后不再繪制脑又,
kCGGradientDrawsAfterEndLocation開始位置之前不進(jìn)行繪制,到結(jié)束點(diǎn)之后繼續(xù)填充
*/
CGContextDrawLinearGradient(context, colorGradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation);
CGGradientRelease(colorGradient);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
如果想對第一個(gè)種方法更深一層研究的話锐借,推薦下面一篇博客
iOS實(shí)現(xiàn)UIView漸變的幾種方法以及實(shí)現(xiàn)漸變透明功能