总结iOS实现渐变颜色的三种方法

在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开发者们能有所帮助,如果有疑问大家可以留言交流。

(0)

相关推荐

  • IOS代码笔记之文字走马灯效果

    本文实例为大家分享了IOS文字走马灯效果具体实现代码,供大家参考,具体内容如下 一.效果图 二.工程图  三.代码 RootViewController.h #import <UIKit/UIKit.h> @interface RootViewController : UIViewController @end RootViewController.m #import "RootViewController.h" #import "UXLabel.h"

  • iOS实现知乎和途家导航栏渐变的文字动画效果

    效果图如下 分析如下: 1.导航栏一开始是隐藏的,随着scrollView滚动而渐变 2.导航栏左右两边的navigationItem是一直显示的 3.导航栏参考了途家app,使用了毛玻璃效果,背景是一张图片 4.下拉放大图片效果 5.title文字动画效果 通过简单分析,系统的导航栏实现以上效果有点困难,直接自定义一个假的导航栏更容易点 分布拆解实现以上效果 一.下拉放大header图片 - (void)viewDidLoad { [super viewDidLoad]; [self.view

  • IOS中一段文字设置多种字体颜色代码

    给定range和需要设置的颜色,就可以给一段文字设置多种不同的字体颜色,使用方法如下: 复制代码 代码如下: [self fuwenbenLabel:contentLabel FontNumber:[UIFont systemFontOfSize:15] AndRange:NSMakeRange(6, 1) AndColor:RGBACOLOR(34, 150, 253, 1)]; 复制代码 代码如下: //设置不同字体颜色 -(void)fuwenbenLabel:(UILabel *)lab

  • iOS中的UITextView文字输入光标使用技巧小结

    1.创建并初始化 @property (nonatomic, strong) UITextView *textView; // 创建 self.textView = [[UITextView alloc] initWithFrame:self.view.frame]; // 设置textview里面的字体颜色 self.textView.textColor = [UIColor blackColor]; // 设置字体名字和字体大小 self.textView.font = [UIFont fo

  • IOS绘制动画颜色渐变折线条

    先给大家展示下效果图: 概述 现状 折线图的应用比较广泛,为了增强用户体验,很多应用中都嵌入了折线图.折线图可以更加直观的表示数据的变化.网络上有很多绘制折线图的demo,有的也使用了动画,但是线条颜色渐变的折线图的demo少之又少,甚至可以说没有.该Blog阐述了动画绘制线条颜色渐变的折线图的实现方案,以及折线图线条颜色渐变的实现原理,并附以完整的示例. 成果 本人已将折线图封装到了一个UIView子类中,并提供了相应的接口.该自定义折线图视图,基本上可以适用于大部分需要集成折线图的项目.若你

  • iOS文字渐变色效果的实现方法

    照例先上文字渐变的效果图 实现思路如下 一.创建一个颜色渐变层,渐变图层跟文字控件一样大. 二.用文字图层裁剪渐变层,只保留文字部分,就会让渐变层只保留有文字的部分,相当于间接让渐变层显示文字,我们看到的其实是被裁剪过后,渐变层的部分内容. 注意:如果用文字图层裁剪渐变层,文字图层就不在拥有显示功能,这个图层就被弄来裁剪了,不会显示,在下面代码中也会有说明. 2.1 创建一个带有文字的label,label能显示文字. 2.2 设置渐变图层的mask为label图层,就能用文字裁剪渐变图层了.

  • iOS中修改UITextField占位符字体颜色的方法总结

    前言 最近学了UITextField控件, 感觉在里面设置占位符非常好, 给用户提示信息, 于是就在想占位符的字体和颜色能不能改变呢?下面是小编的一些简单的实现,有需要的朋友们可以参考. 修改UITextField的占位符文字颜色主要有三个方法: 1.使用attributedPlaceholder属性 @property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder NS_AVAILABLE_IOS(6_0

  • iOS实现文字转化成彩色文字图片

    本文写了个将文字转化为多彩图片的功能,输入文字将文字转化为彩色的文字图片,可选择不同的字体,渐变,先看看效果. 实现主要用CAGradientLayer渐变,先看看上部展示实现代码: -(void)setupContentView { UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, ScreenWidth, ScreenHight - 44 -300)]; [self.view addSubview:co

  • iOS应用中UILabel文字显示效果的常用设置总结

    创建UIlabel对象 复制代码 代码如下: UILabel* label = [[UILabel alloc] initWithFrame:self.view.bounds]; 设置显示文本 复制代码 代码如下: label.text = @"This is a UILabel Demo,"; 设置文本字体 复制代码 代码如下: label.font = [UIFont fontWithName:@"Arial" size:35]; 设置文本颜色 复制代码 代码如

  • iOS - UIButton(UIEdgeInsets)/设置button上的文字和图片上下垂直居中对齐

    UIEdgeInsets typedef struct UIEdgeInsets { CGFloat top, left, bottom, right; // specify amount to inset (positive) for each of the edges. values can be negative to 'outset' } UIEdgeInsets; 在UIButton中有三个对EdgeInsets的设置:ContentEdgeInsets.titleEdgeInsets

随机推荐