总结iOS实现渐变颜色的三种方法_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开发者们能有所帮助,如果有疑问大家可以留言交流。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索ios
颜色渐变
ps三种颜色渐变、css三种颜色渐变、三种颜色渐变、js实现颜色渐变、css实现颜色渐变,以便于您获取更多的相关知识。

时间: 2024-08-30 18:25:47

总结iOS实现渐变颜色的三种方法_IOS的相关文章

iOS毛玻璃效果的实现及图片模糊效果的三种方法_IOS

App设计时往往会用到一些模糊效果或者毛玻璃效果,iOS目前已提供一些模糊API可以让我们方便是使用. 话说苹果在iOS7.0之后,很多系统界面都使用了毛玻璃效果,增加了界面的美观性,比如下图的通知中心界面; 但是其iOS7.0的SDK并没有提供给开发者实现毛玻璃效果的API,所以很多人都是通过一些别人封装的框架来实现,后面我也会讲到一个; 其实在iOS7.0(包括)之前还是有系统的类可以实现毛玻璃效果的, 就是 UIToolbar这个类,并且使用相当简单,几行代码就可以搞定. 下面是代码实现:

在IOS中为什么使用多线程及多线程实现的三种方法_IOS

多线程是一个比较轻量级的方法来实现单个应用程序内多个代码执行路径. 在系统级别内,程序并排执行,程序分配到每个程序的执行时间是基于该程序的所需时间和其他程序的所需时间来决定的. 然而,在每个程序内部,存在一个或者多个执行线程,它同时或在一个几乎同时发生的方式里执行不同的任务. 概要提示: iPhone中的线程应用并不是无节制的,官方给出的资料显示,iPhone OS下的主线程的堆栈大小是1M,第二个线程开始就是512KB,并且该值不能通过编译器开关或线程API函数来更改,只有主线程有直接修改UI

iOS开发中Swift3 监听UITextView文字改变的方法(三种方法)_IOS

在项目中使用文本输入框出UITextField之外还会经常使用 UITextView ,难免会有需求监听UITextView文本框内文本数量.下面介绍在swift3中两种常用方式 方式一: 全局通知 1.注册通知 在合适位置注册监听UITextView文本变化的全局通知 //UITextView 监听开始输入的两种方法 //方法一:通知 NotificationCenter.default.addObserver(self, selector: #selector(ComposeVC.textV

iOS 拨打电话代码的三种方式_IOS

 1,这种方式,拨打完电话回不到原来的应用,会停留在通讯录里,而且是直接拨打,不弹出提示 NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"186xxxxxxxx"]; // NSLog(@"str======%@",str); [[UIApplication sharedApplication] openURL:[NSURL URLWithStri

IOS collectionViewCell防止复用的两种方法_IOS

IOS collectionViewCell防止复用的两种方法 collectionView 防止cell复用的方法一: //在创建collectionView的时候注册cell(一个分区) UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; for (UIView *view in cell.contentV

jquery交替变换颜色的三种方法 实例代码_jquery

复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="

Android开发笔记 改变字体颜色的三种方法_Android

1.在layout文件下的配置xml文件中直接设置字体颜色,通过添加android:textcolor="#FFFFFF"来变化颜色 但这样的效果只能让字体千篇一律的显示一种颜色 2.在activity中通过TextView tv=new TextView(this):实例化一个textview,通过setContentView(tv);将其加载到当前activity,设置要显示的内容String str="想要显示的内容":通过以下代码可以实现部分文本字体的改变,

iOS开发定时器的三种方法分享_IOS

前言 在开发中,很多时候我们需要用到定时器实时刷新某个数值.这个时候我们就需要用到定时器,这里,我为大家推荐三种方法,分别是:NSTimer.CADisplayLink.GCD.接下来我就一一介绍它们的用法.希望能帮到大家. 一.NSTimer(一般用于定时的更新一些非界面上的数据) 1. 创建方法 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:

iOS 设备唯一 ID 的三种替代方法之一

iOS 设备唯一 ID 的三种替代方法之一 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. [UIDeviceuniqueIdentifier] 文档中指明的替代方法之一(一共有三个替代方法):