控件渐变色的实现(二)—— Core Graphics实现

版本记录

版本号 时间
V1.0 2017.08.07

前言

很多时候视图的颜色并不是单一的,需要渐变或者更炫的色彩,这里我就说一下控件渐变色的实现方法。希望能帮助大家。感兴趣的可以看我上一篇文章。
1. 控件渐变色的实现(一)—— CAGradientLayer实现

功能要求

利用Core Graphics控件渐变色的实现。


功能实现

Core Graphics中有两个方法用于绘制渐变颜色:

  • CGContextDrawLinearGradient可以用于生成线性渐变。
  • CGContextDrawRadialGradient用于生成圆半径方向颜色渐变。

函数可以自定义path,无论是什么形状都可以,原理都是用来做Clip,所以需要在CGContextClip函数前调用CGContextAddPath函数把CGPathRef加入到Context中。

另外一个需要注意的地方是渐变的方向,方向是由两个点控制的,点的单位就是坐标。因此需要正确从CGPathRef中找到正确的点,方法当然有很多种看具体实现,下面方法中,我就是简单得通过调用CGPathGetBoundingBox函数,返回CGPathRef的矩形区域,然后根据这个矩形取两个点。

1. 线性渐变

还是直接看代码。

#import "JJGradientGraphicVC.h"
#import "Masonry.h"

@interface JJGradientGraphicVC ()

@end

@implementation JJGradientGraphicVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"线性渐变色";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //创建CGContextRef
    UIGraphicsBeginImageContext(self.view.bounds.size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    //创建CGMutablePathRef
    CGMutablePathRef pathRef = CGPathCreateMutable();
    
    //绘制path
    CGRect rect = CGRectMake(50.0, 100.0, 300.0, 250.0);
    CGPathMoveToPoint(pathRef, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
    CGPathCloseSubpath(pathRef);
    
    //绘制渐变色
    [self drawLinearGradientWithContext:contextRef path:pathRef beginColor:[UIColor redColor].CGColor endColor:[UIColor greenColor].CGColor];
    
    //释放CGMutablePathRef
    CGPathRelease(pathRef);
    
    //从上下文中获取图像并显示
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.view addSubview:imageView];

    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.width.equalTo(@300);
        make.height.equalTo(@250);
    }];
}

#pragma mark - Object Private Function

- (void)drawLinearGradientWithContext:(CGContextRef)context
                                 path:(CGPathRef)path
                           beginColor:(CGColorRef)beginColor
                             endColor:(CGColorRef)endColor;
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = {0.0, 1.0};
    NSArray *colorArr = @[(__bridge id)beginColor, (__bridge id)endColor];
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colorArr, 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, gradientRef, startPoint, endPoint, 0);
    CGContextRestoreGState(context);
    
    CGGradientRelease(gradientRef);
    CGColorSpaceRelease(colorSpace);
}

@end

效果图验证会在后面给出。

这里重要的是函数CGContextDrawLinearGradient

/** Gradient and shading functions. **/

/* Fill the current clipping region of `context' with a linear gradient from
   `startPoint' to `endPoint'. The location 0 of `gradient' corresponds to
   `startPoint'; the location 1 of `gradient' corresponds to `endPoint';
   colors are linearly interpolated between these two points based on the
   values of the gradient's locations. The option flags control whether the
   gradient is drawn before the start point or after the end point. */

CG_EXTERN void CGContextDrawLinearGradient(CGContextRef cg_nullable c,
    CGGradientRef cg_nullable gradient, CGPoint startPoint, CGPoint endPoint,
    CGGradientDrawingOptions options)
    CG_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

这个方法的作用是:使用线性渐变填充当前的“上下文”剪切区域startPointendPoint。 “渐变”的位置0对应于 的startPointgradient的位置1对应于endPoint, 颜色在这两点之间基于线性插值渐变位置的值。 选项标志控制是否梯度在起始点或终点之后绘制。

2. 圆半径外向渐变

这个可以认为是非线性渐变中的一种。

#import "JJGradientNonliearVC.h"
#import "Masonry.h"

@interface JJGradientNonliearVC ()

@end

@implementation JJGradientNonliearVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"非线性渐变色";
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    //创建CGContextRef
    UIGraphicsBeginImageContext(self.view.bounds.size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    //创建CGMutablePathRef
    CGMutablePathRef pathRef = CGPathCreateMutable();
    
    //绘制path
    CGRect rect = CGRectMake(50.0, 100.0, 300.0, 250.0);
    CGPathMoveToPoint(pathRef, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
    CGPathAddLineToPoint(pathRef, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect));
    CGPathCloseSubpath(pathRef);
    
    //绘制渐变色
    [self drawRadiusGradientWithContext:contextRef path:pathRef beginColor:[UIColor redColor].CGColor endColor:[UIColor greenColor].CGColor];
    
    //释放CGMutablePathRef
    CGPathRelease(pathRef);
    
    //从上下文中获取图像并显示
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:imageView];
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.width.equalTo(@300);
        make.height.equalTo(@250);
    }];
}

#pragma mark - Object Private Function

- (void)drawRadiusGradientWithContext:(CGContextRef)context
                                 path:(CGPathRef)path
                           beginColor:(CGColorRef)beginColor
                             endColor:(CGColorRef)endColor;
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = {0.0, 1.0};
    NSArray *colorArr = @[(__bridge id)beginColor, (__bridge id)endColor];
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colorArr, locations);
    CGRect pathRect = CGPathGetBoundingBox(path);
    
    //具体方向可根据需求修改
    CGPoint centerPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMidY(pathRect));
    CGFloat radius = MAX(pathRect.size.width * 0.5, pathRect.size.height * 0.5) * sqrt(2);
    
    CGContextSaveGState(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawRadialGradient(context, gradientRef, centerPoint, 0, centerPoint, radius, 0);
    CGContextRestoreGState(context);
    
    CGGradientRelease(gradientRef);
    CGColorSpaceRelease(colorSpace);
}

@end

后面会给出这个效果图。

这里重要的函数是CGContextDrawRadialGradient(context, gradientRef, centerPoint, 0, centerPoint, radius, 0);

/* Fill the current clipping region of `context' with a radial gradient
   between two circles defined by the center point and radius of each
   circle. The location 0 of `gradient' corresponds to a circle centered at
   `startCenter' with radius `startRadius'; the location 1 of `gradient'
   corresponds to a circle centered at `endCenter' with radius `endRadius';
   colors are linearly interpolated between these two circles based on the
   values of the gradient's locations. The option flags control whether the
   gradient is drawn before the start circle or after the end circle. */

CG_EXTERN void CGContextDrawRadialGradient(CGContextRef cg_nullable c,
    CGGradientRef cg_nullable gradient, CGPoint startCenter, CGFloat startRadius,
    CGPoint endCenter, CGFloat endRadius, CGGradientDrawingOptions options)
    CG_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

它的作用是:用径向渐变填充当前的“上下文”裁剪区域 在由中心点和每个半径定义的两个圆之间圈。 “渐变”的位置0对应于以圆为中心的圆 startCenter,半径为startRadius; “渐变”的位置1对应于以endCenter为中心的圆圈,半径为endRadius; 基于此,这两个圆之间的颜色被线性内插 渐变位置的值。 选项标志控制是否梯度在起始圆之前或结束圆之后绘制。


功能效果

先看一下线性渐变的效果。

线性渐变

下面看一下圆半径外向渐变色效果。

圆半径外向渐变

可见,均可实现效果。

后记

未完,待续~~~

秋意浓
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容