總結iOS實現漸層顏色的三種方法_IOS

來源:互聯網
上載者:User

在iOS開發過程中有的時候會需要用到漸層的顏色,這篇文章總結了三種方法來實現,有需要的朋友們下面來一起看看吧。

一、CAGradientLayer實現漸層

CAGradientLayer是CALayer的一個特殊子類,用於產生色彩坡形的圖層,使用較為方便

下面介紹下它的相關屬性:

      colors 漸層的顏色

      locations 漸層顏色的分割點

      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實現漸層標間簡單直觀,但存在一定的局限性,比如無法自訂整個漸層地區的形狀,如環形、曲線形的漸層。

二、Core Graphics相關方法實現漸層

iOS Core Graphics中有兩個方法用於繪製漸層顏色,CGContextDrawLinearGradient可以用於產生線性漸層,CGContextDrawRadialGradient用於產生圓半徑方向色彩坡形。函數可以自訂path,無論是什麼形狀都可以,原理都是用來做Clip,所以需要在CGContextClip函數前調用CGContextAddPath函數把CGPathRef加入到Context中。
另外一個需要注意的地方是漸層的方向,方向是由兩個點控制的,點的單位就是座標。因此需要正確從CGPathRef中找到正確的點,方法當然有很多種看具體實現,本例中,我就是簡單得通過調用CGPathGetBoundingBox函數,返回CGPathRef的矩形地區,然後根據這個矩形取兩個點,讀者可以根據自行需求修改具體代碼。

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); //具體方向可根據需求修改 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. //建立CGContextRef UIGraphicsBeginImageContext(self.view.bounds.size); CGContextRef gc = UIGraphicsGetCurrentContext(); //建立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. //建立CGContextRef UIGraphicsBeginImageContext(self.view.bounds.size); CGContextRef gc = UIGraphicsGetCurrentContext(); //建立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對象用作layer的mask屬性的話,就可以產生不同形狀的圖層。

故產生色彩坡形有以下幾個步驟:

     1、產生一個imageView(也可以為layer),image的屬性為色彩坡形的圖片

     2、產生一個CAShapeLayer對象,根據path屬性指定所需的形狀

     3、將CAShapeLayer對象賦值給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;}

總結

以上就是這篇文章的全部內容了,希望本文的內容對各位iOS開發人員們能有所協助,如果有疑問大家可以留言交流。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.