總結(jié)iOS實(shí)現(xiàn)漸變顏色的三種方法
在iOS開發(fā)過程中有的時(shí)候會(huì)需要用到漸變的顏色,這篇文章總結(jié)了三種方法來(lái)實(shí)現(xiàn),有需要的朋友們下面來(lái)一起看看吧。
一、CAGradientLayer實(shí)現(xiàn)漸變
CAGradientLayer是CALayer的一個(gè)特殊子類,用于生成顏色漸變的圖層,使用較為方便
下面介紹下它的相關(guān)屬性:
colors 漸變的顏色
locations 漸變顏色的分割點(diǎn)
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); [self.view.layer addSublayer:gradientLayer];

CAGradientLayer實(shí)現(xiàn)漸變標(biāo)間簡(jiǎn)單直觀,但存在一定的局限性,比如無(wú)法自定義整個(gè)漸變區(qū)域的形狀,如環(huán)形、曲線形的漸變。
二、Core Graphics相關(guān)方法實(shí)現(xiàn)漸變
iOS Core Graphics中有兩個(gè)方法用于繪制漸變顏色,CGContextDrawLinearGradient可以用于生成線性漸變,CGContextDrawRadialGradient用于生成圓半徑方向顏色漸變。函數(shù)可以自定義path,無(wú)論是什么形狀都可以,原理都是用來(lái)做Clip,所以需要在CGContextClip函數(shù)前調(diào)用CGContextAddPath函數(shù)把CGPathRef加入到Context中。
另外一個(gè)需要注意的地方是漸變的方向,方向是由兩個(gè)點(diǎn)控制的,點(diǎn)的單位就是坐標(biāo)。因此需要正確從CGPathRef中找到正確的點(diǎn),方法當(dāng)然有很多種看具體實(shí)現(xiàn),本例中,我就是簡(jiǎn)單得通過調(diào)用CGPathGetBoundingBox函數(shù),返回CGPathRef的矩形區(qū)域,然后根據(jù)這個(gè)矩形取兩個(gè)點(diǎn),讀者可以根據(jù)自行需求修改具體代碼。
1-> 線性漸變
- (void)drawLinearGradient:(CGContextRef)context
path:(CGPathRef)path
startColor:(CGColorRef)startColor
endColor:(CGColorRef)endColor
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
CGRect pathRect = CGPathGetBoundingBox(path);
//具體方向可根據(jù)需求修改
CGPoint startPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMidY(pathRect));
CGPoint endPoint = CGPointMake(CGRectGetMaxX(pathRect), CGRectGetMidY(pathRect));
CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//創(chuàng)建CGContextRef
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
//創(chuàng)建CGMutablePathRef
CGMutablePathRef path = CGPathCreateMutable();
//繪制Path
CGRect rect = CGRectMake(0, 100, 300, 200);
CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMaxY(rect));
CGPathCloseSubpath(path);
//繪制漸變
[self drawLinearGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];
//注意釋放CGMutablePathRef
CGPathRelease(path);
//從Context中獲取圖像,并顯示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];
}

2-> 圓半徑方向漸變
- (void)drawRadialGradient:(CGContextRef)context
path:(CGPathRef)path
startColor:(CGColorRef)startColor
endColor:(CGColorRef)endColor
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
CGRect pathRect = CGPathGetBoundingBox(path);
CGPoint center = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMidY(pathRect));
CGFloat radius = MAX(pathRect.size.width / 2.0, pathRect.size.height / 2.0) * sqrt(2);
CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextEOClip(context);
CGContextDrawRadialGradient(context, gradient, center, 0, center, radius, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//創(chuàng)建CGContextRef
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
//創(chuàng)建CGMutablePathRef
CGMutablePathRef path = CGPathCreateMutable();
//繪制Path
CGRect rect = CGRectMake(0, 100, 300, 200);
CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMaxY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMinY(rect));
CGPathCloseSubpath(path);
//繪制漸變
[self drawRadialGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];
//注意釋放CGMutablePathRef
CGPathRelease(path);
//從Context中獲取圖像,并顯示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];
}

三、以CAShapeLayer作為layer的mask屬性
CALayer的mask屬性可以作為遮罩讓layer顯示mask遮住(非透明)的部分;CAShapeLayer為CALayer的子類,通過path屬性可以生成不同的形狀,將CAShapeLayer對(duì)象用作layer的mask屬性的話,就可以生成不同形狀的圖層。
故生成顏色漸變有以下幾個(gè)步驟:
1、生成一個(gè)imageView(也可以為layer),image的屬性為顏色漸變的圖片
2、生成一個(gè)CAShapeLayer對(duì)象,根據(jù)path屬性指定所需的形狀
3、將CAShapeLayer對(duì)象賦值給imageView的mask屬性
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:self.firstCircle];
_firstCircle.frame = CGRectMake(0, 0, 200, 200);
_firstCircle.center = CGPointMake(CGRectGetWidth(self.view.bounds) / 2.0, CGRectGetHeight(self.view.bounds) / 2.0);
CGFloat firsCircleWidth = 5;
self.firstCircleShapeLayer = [self generateShapeLayerWithLineWidth:firsCircleWidth];
_firstCircleShapeLayer.path = [self generateBezierPathWithCenter:CGPointMake(100, 100) radius:100].CGPath;
_firstCircle.layer.mask = _firstCircleShapeLayer;
}
- (CAShapeLayer *)generateShapeLayerWithLineWidth:(CGFloat)lineWidth
{
CAShapeLayer *waveline = [CAShapeLayer layer];
waveline.lineCap = kCALineCapButt;
waveline.lineJoin = kCALineJoinRound;
waveline.strokeColor = [UIColor redColor].CGColor;
waveline.fillColor = [[UIColor clearColor] CGColor];
waveline.lineWidth = lineWidth;
waveline.backgroundColor = [UIColor clearColor].CGColor;
return waveline;
}
- (UIBezierPath *)generateBezierPathWithCenter:(CGPoint)center radius:(CGFloat)radius
{
UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0 endAngle:2*M_PI clockwise:NO];
return circlePath;
}
- (UIImageView *)firstCircle
{
if (!_firstCircle) {
self.firstCircle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"circleBackground"]];
_firstCircle.layer.masksToBounds = YES;
_firstCircle.alpha = 1.0;
}
return _firstCircle;
}

總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)各位iOS開發(fā)者們能有所幫助,如果有疑問大家可以留言交流。
- 詳解iOS中Button按鈕的狀態(tài)和點(diǎn)擊事件
- 關(guān)于iOS導(dǎo)航欄返回按鈕問題的解決方法
- IOS UITableViewCell詳解及按鈕點(diǎn)擊事件處理實(shí)例
- 詳解iOS-按鈕單選與多選邏輯處理
- IOS 開發(fā)之自定義按鈕實(shí)現(xiàn)文字圖片位置隨意定制
- iOS 底部按鈕和應(yīng)用圖標(biāo)顯示未讀消息(帶數(shù)字)
- IOS繪制動(dòng)畫顏色漸變折線條
- iOS快速實(shí)現(xiàn)環(huán)形漸變進(jìn)度條
- iOS文字漸變色效果的實(shí)現(xiàn)方法
- iOS實(shí)現(xiàn)漸變按鈕Gradient Button的方法示例
相關(guān)文章
iOS中解決Xcode9的Log日志無(wú)法輸出中文的問題小結(jié)
這篇文章主要介紹了iOS中解決Xcode9的Log日志無(wú)法輸出中文的問題小結(jié),需要的朋友可以參考下2017-11-11
使用Xcode為iOS應(yīng)用項(xiàng)目創(chuàng)建PCH文件的方法及應(yīng)用示例
這篇文章主要介紹了使用Xcode為iOS應(yīng)用項(xiàng)目創(chuàng)建PCH文件的方法及應(yīng)用示例,PCH文件可以保留應(yīng)用的很多的基礎(chǔ)設(shè)置信息以供復(fù)用,需要的朋友可以參考下2016-03-03
iOS應(yīng)用開發(fā)中使用設(shè)計(jì)模式中的觀察者模式的實(shí)例
這篇文章主要介紹了iOS應(yīng)用開發(fā)中使用設(shè)計(jì)模式中的觀察者模式的實(shí)例,包括Cocoa框架使用中的KVO機(jī)制的相關(guān)配合運(yùn)用,代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-03-03
iOS開發(fā)中仿Tumblr點(diǎn)贊心破碎動(dòng)畫效果
這篇文章主要介紹了iOS開發(fā)中仿Tumblr點(diǎn)贊心破碎動(dòng)畫效果,本文圖文并茂給大家介紹的非常詳細(xì),需要的朋友可以參考下2017-04-04
iOS tableView實(shí)現(xiàn)單選和多選的實(shí)例代碼
本篇文章主要介紹了iOS tableView實(shí)現(xiàn)單選和多選的實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-07-07
iOS?項(xiàng)目嵌入Flutter?運(yùn)行(最新推薦)
這篇文章主要介紹了iOS?項(xiàng)目嵌入Flutter?運(yùn)行,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
iOS10 適配遠(yuǎn)程推送功能實(shí)現(xiàn)代碼
這篇文章主要介紹了iOS10 適配遠(yuǎn)程推送功能實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09

