UIImage+Extension.swift
import UIKit
extension UIImage
{
// 改变图片的颜色
class func imageWithColor(imageName:String, color: UIColor) -> UIImage
{
let image = UIImage(named: imageName)!
UIGraphicsBeginImageContext(image.size)
let context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, image.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, .Normal);
let rect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextClipToMask(context, rect, image.CGImage);
color.setFill()
CGContextFillRect(context, rect);
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
}
private func creatBtn(imageName: String) -> UIButton
{
let btn = UIButton()
btn.setImage(UIImage.imageWithColor(imageName, color: UIColor.blackColor()), forState: .Normal)
return btn
}
获取上下文,图形上下文是什么意思?
CGContextRef context = UIGraphicsGetCurrentCont
画一个正方形图形 没有边框
CGContextSetRGBFillColor
CGContextFillRect(context, CGRectMake(2, 2, 270, 270));
CGContextStrokePath(context);
写文字
CGContextSetLineWidth(context, 1.0);
CGContextSetRGBFillColor
UIFont
[@"fangyp" drawInRect:CGRectMake(40, 40, 80, 20) withFont:font];
画一条线
CGContextSetRGBStrokeCol
CGContextMoveToPoint(context, 20, 20);
CGContextAddLineToPoint(context, 200,20);
CGContextStrokePath(context);
画正方形边框
CGContextSetRGBStrokeCol
CGContextSetLineWidth(context, 2.0);
CGContextAddRect(context, CGRectMake(2, 2, 270, 270));
CGContextStrokePath(context);
画方形背景颜色
UIGraphicsPopContext();
1、画线:在uiview类里重写下面方法
-(void)drawRect:(CGRect)rect
{
//
//
//
//
2、弧线 CGContextAddArcToPoint与CGContextAddArc
void
x,y为圆点坐标,startAngle为开始的弧度,endAngle为
以下是示例代码。
CGContextBeginPath(context);
CGContextSetRGBStrokeCol
CGContextAddArc(context, 100, 100, 50, 180* PI/ 180, 270* PI/ 180,0);
CGContextStrokePath(context);
void
首先使用该函数绘制圆弧前,首先要确定一个start point.
CGContextMoveToPoint(context, 100, 100);
然后设置CGContextAddArcToPoint(context, 50, 100, 50, 150, 50);
这里是从起始点100,100开始到第一个点50,100画一条线段,然后再从第一个点50,100到第二点150,50画另一条线段(这是两条相交切线),然后设置半径为50.通过相交的两条线段和半径就可以确定圆弧了。
示例代码如下:
CGContextBeginPath(context);
CGContextSetRGBStrokeCol
CGContextMoveToPoint(context, 100, 100);
CGContextAddArcToPoint(context, 50, 100, 50, 150, 50);
CGContextStrokePath(context);
注意:Path被绘制后,当前点的坐标更改为150,50
CGContextRef context = UIGraphicsGetCurrentCont
CGContextMoveToPoint 开始画线
CGContextAddLineToPoint 画直线
4 CGContextAddEllipseInRec
4 CGContextSetLineCap 设置线条终点形状
4 CGContextSetLineDash 画虚线
4 CGContextAddRect 画一方框
4 CGContextStrokeRect 指定矩形
4 CGContextStrokeRectWithW
4 CGContextStrokeLineSegme
5 CGContextAddArc 画已曲线 前俩店为中心 中间俩店为起始弧度 最后一数据为0则顺时针画 1则逆时针
5 CGContextAddArcToPoint(context,0,0, 2, 9, 40);//先画俩条线从point 到 弟1点 , 从弟1点到弟2点的线
6 CGContextSetShadowWithCo
7 CGContextSetRGBFillColor
7 CGContextSetRGBStrokeCol
7 CGContextSetFillColorSpa
7 CGConextSetStrokeColorSp
8 CGContextFillRect 补充当前填充颜色的rect
8 CGContextSetAlaha 透明度
9 CGContextTranslateCTM 改变画布位置
10 CGContextSetLineWidth 设置线的宽度
11 CGContextAddRects 画多个线
12 CGContextAddQuadCurveToP
13
13 CGContextDrawPath 设置绘制模式
14 CGContextClosePath 封闭当前线路
15 CGContextTranslateCTM(context, 0, rect.size.height);
16 CGContextSetInterpolatio
16 CGImageCreateWithImageIn
17 字符串的 写入可用
18对图片放大缩小的功能就是慢了点
19 CGColorGetComponents() 返回颜色的各个直 以及透明度 可用只读const float 来接收
20 画图片 CGImageRef image=CGImageRetain(img.CGImage);
21 实现逐变颜色填充方法 CGContextClip(context);
22 注:
填充一个路径的时候,路径里面的子路径都是独立填充的。
假如是重叠的路径,决定一个点是否被填充,有两种规则
1,nonzero winding number rule:非零绕数规则,假如一个点被从左到右跨过,计数器+1,从右到左跨过,计数器-1,最后,如果结果是0,那么不填充,如果是非零,那么填充。
2,even-odd rule: 奇偶规则,假如一个点被跨过,那么+1,最后是奇数,那么要被填充,偶数则不填充,和方向没有关系。
Description
设置当一个颜色覆盖上另外一个颜色,两个颜色怎么混合
默认方式是
result = (alpha * foreground) + (1 - alpha) * background
CGContextSetBlendMode :设置blend mode.
CGContextSaveGState :保存blend mode.
CGContextRestoreGState:在没有保存之前,用这个函数还原blend mode.
CGContextSetBlendMode 混合俩种颜色
下面是iOS中利用UIGraphicsBeginImageContextWithOptions来剪裁成圆型位图并返回的代码
+ (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor { // 1.加载原图 UIImage *oldImage = [UIImage imageNamed:name]; // 2.开启上下文 CGFloat imageW = oldImage.size.width + 2 * borderWidth; CGFloat imageH = oldImage.size.height + 2 * borderWidth; CGSize imageSize = CGSizeMake(imageW, imageH); UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0); // 3.取得当前的上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 4.画边框(大圆) [borderColor set]; CGFloat bigRadius = imageW * 0.5; // 大圆半径 CGFloat centerX = bigRadius; // 圆心 CGFloat centerY = bigRadius; CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0); CGContextFillPath(ctx); // 画圆 // 5.小圆 CGFloat smallRadius = bigRadius - borderWidth; CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0); // 裁剪(后面画的东西才会受裁剪的影响) CGContextClip(ctx); // 6.画图 [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)]; // 7.取图 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); // 8.结束上下文 UIGraphicsEndImageContext(); return newImage; }
当然在iOS中,我们完全可以pass掉这些晦涩难懂的底层代码,因为系统给我们提供了更高一级的函数来生成PDF文件,下面是代码
1 - (void)createPDFFile 2 { 3 // 1. 上下文 4 // 1) 路径 5 // 2) 大小,指定为空,那么使用612 * 792大小作为pdf文件的页面大小 6 // 3) dict 7 UIGraphicsBeginPDFContextToFile(@"/Users/apple/Desktop/demo.pdf", CGRectZero, nil); 8 9 // 2. 写入内容 10 // 在pdf里面是有页面的,一个页面一个页面的写入的 11 // 建立PDF页面 12 // 一个页面最多能够写入两张图片,因此写入6张图片需要三个页面 13 for (NSInteger i = 0; i < 6; i++) { 14 if (i % 2 == 0) { 15 UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil); 16 } 17 18 // 生成UIImage 19 UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"NatGeo%02d.png", i + 1]]; 20 // 写入 21 [image drawAtPoint:CGPointMake(0, 400 * (i % 2))]; 22 } 23 24 // 3. 关闭上下文 25 UIGraphicsEndPDFContext(); 26 }
深入理解图形上下文
CGContextRef
结构体
,携带Quartz 2D引擎进行一次绘图操作所需的信息
。这些信息可以分为三部分:- 画在哪里?即
绘图目标
,可以是图层
(CALayer),应用窗口
(OS X),位图图像
,PDF文件
以及打印机
。这部分信息不可修改
。 - 画些什么?即
绘图路径
,可以是UIBezierPath
(OC)或者CGPathRef
(C)对象。每次执行绘图操作后,这部分信息被自动清空。 - 用什么画?即
绘图状态
,包括线宽,颜色,样式,CTM
,裁剪路径等。每次执行绘图操作后,如果不被新的信息覆盖,将继续沿用上次的信息
。
- 画在哪里?即
// 绘图流程
创建路径对象--->
获取当前上下文--->
配置绘图状态信息,如CTM--->
显式/隐式的将路径添加至上下文--->
下达绘图指令。
获取/创建上下文
图层上下文(CALayer)
- 只有在调用drawRect(UIView),drawInContext:(CALayer),drawLayer:inContext:(CALayerDelegate)方法时,才能通过
UIGraphicsGetCurrentContext
函数获取到上下文栈中的当前上下文。 - 图层上下文不能手动创建。
位图上下文(bitmap图像)
- 可以在
任何地方
创建位图上下文。 - 通过
UIGraphicsBeginImageContextWithOptions
手动创建一个位图上下文,并将其推入上下文栈中
。 - 通过
UIGraphicsGetImageFromCurrentImageContext
从位图上下文中获取所绘制的图像对象
。 - 使用完毕,调用
UIGraphicsEndImageContext
将位图上下文从栈上弹出
。
- (void)modifyImageAndDrawSomewhere
{
// 获取原始图片
UIImage *img = [UIImage imageNamed:@"aim"];
/**
设置位图(画布)大小,即最重获取到的图片的尺寸。
注意,图像只能缩小,放大后会失真。
*/
CGSize targetSize = CGSizeMake(50, 50);
// 开启一个位图上下文,大小为画布大小,不透明,缩放系数参照当前设备
UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);
// 将原始图片绘制到当前下上文中(位图上下文),
// 注意这里的尺寸一定要和画布尺寸相同
[img drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height)];
// 从当前位图上下文中获取绘制完成的位图对象(原始图片滚蛋了)
img = UIGraphicsGetImageFromCurrentImageContext();
/**
结束位图上下文(弹出栈)
这个函数在将位图上下文弹出栈的同时,还会进行一些清理工作,
所以不能使用UIGraphicsPopContext,其只能与UIGraphicsPushContext配合使用。
*/
UIGraphicsEndImageContext();
// 将处理过后的图像塞给image view
self.imageView.image = img; // 或者让图像在图层上下文中绘制,当然要在drawRect:方法中实现
/**
将新的图像转换为二进制数据,写入磁盘。
注意,使用UIImagePNGRepresentation()和UIImageJPEGRepresentation()将图片对象转化为数据时,
二者的区别在于png支持透明,而jpeg不支持。
*/
NSData *data = UIImagePNGRepresentation(img);
[data writeToFile:filePath atomically:YES];
}
构建路径
- 路径的默认轮廓和填充颜色为
黑色
,轮廓线条的默认宽度为1个单位
。 - OC方式创建的路径对象可以直接绘制,不需显式的添加至图形上下文;而C方式创建的路径对象必须通过CGContextRef的
CGContextAddPath
函数添加。
UIBezierPath ( OC )
-
创建路径:
bezierPath
bezierPathWithCGPath:
(通过CGPathRef创建)bezierPathByReversingPath
(反方向绘制路径)bezierPathWithArcCenter:radius:startAngle:endAngle:clockwise:
中的起始角度和结束角度用一个圆当中的位置来表示:- 3点钟:0 PI / 2 PI
- 6点钟:1/2 PI
- 9点钟:PI
- 12点钟:3/2 PI
// 从0 PI开始,绘制到PI // 如果顺时针绘制,则显示下半个圆 // 如果逆时针绘制,则显示上半个圆
-
由于坐标系不同,
CGContextAddArc()
函数对顺时针和逆时针的理解正好同上面的方法相反
,其他相同。 -
bezierPathWithRoundedRect:cornerRadius:
中可以设置圆角半径coner radius
。注意,当这个值大于等于圆半径的2/3
时,矩形变成一个圆形
。(仅限于矩形是正方形)
- 添加子路径:
closePath
removeAllPoints
appendPath:
(拼接另一个路径对象)
- 设置上下文状态:
usesEvenOddFillRule
(使用奇偶规则)
- 绘制路径:
fill / stroke
(调用时,绘图之前会自动保存当前上下文,并在操作完成后将其恢复到之前的状态)
- 点击测试:
containsPoint:
(某个点是否处于路径"内部")empty
(路径是否包含有效元素)
CGPathRef ( C )
- 创建路径:
CGPathCreateMutable
CGPathCreateCopy
CGPathCreateMutableCopy
- 其他几何图形路径。
- 添加子路径:
CGPathAddArcToPoint
CGPathAddEllipseInRect
- 其他函数:
CGPathCloseSubpath
(闭合子路径)
CTM(Current Transformation Matrix)
- 用于将
绘图坐标系映射至视图坐标系
。(视图坐标系
又负责映射至物理坐标系
,即显示设备) - 当前图形上下文被创建后,一个
同视图坐标系完全对应的坐标系
也同时被定义,所有的绘图操作都是参照这个坐标系
进行的。 绘图坐标系
和视图坐标系
的对应关系由CTM决定。改变CTM的值,会导致在内容映射
至视图后,发生扭曲变形。- 视图坐标系是
固定
不变的。CTM以绘图坐标系的原点
为中心,进行旋转,缩放,平移等操作,然后再投射到视图上。 - 注意CTM生效的时机,例如,使用
CGContextAddPath
为上下文添加路径时,Quartz会先根据CTM对路径作处理
,然后再将其添加进上下文
。示例代码如下:
- (void)drawRect:(CGRect)rect
{
// 创建一个可变路径对象
CGMutablePathRef path = CGPathCreateMutable();
// 移动至特定点
CGPathMoveToPoint(path, NULL, 100, 100);
// 连一条直线
CGPathAddLineToPoint(path, NULL, 200, 200);
// 获取当前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
/**
1. 旋转上下文绘图坐标系,注意,必须在将路径添加至上下文之前对坐标系进行旋转,
否则没有效果。
*/
CGContextRotateCTM(ctx, M_PI_4 * 0.5);
/**
2.改变上下文绘图坐标系的原点,注意,必须在将路径添加至上下文之前修改坐标系的原点,
否则没有效果。
*/
CGContextTranslateCTM(ctx, 30, 30);
// 向上下文中添加路径
CGContextAddPath(ctx, path);
/**
3. 修改上下文绘图坐标系的缩放系数,可以在任意时候修改。
*/
CGContextScaleCTM(ctx, 0.5, 4);
// 配置上下文状态信息
CGContextSetLineWidth(ctx, 10);
CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
// 根据上下文绘制路径
CGContextStrokePath(ctx);
/**
注意释放路径对象,
CF对象暂时不受ARC管辖。
这里也可以使用静态分析其查看潜在的内存泄漏
*/
CFBridgingRelease(path); // 或CGPathRelease(path) 或CFRelease(path)
}
裁剪路径
- 用于定义图形上下文中
执行绘图操作的区域
。 - 将
当前路径
作为裁剪路径使用:addClip:
(UIBezierPath)CGContextClip
(CGContextRef)
- 一旦被作为裁剪路径使用,上下文的当前路径属性会被清空。
- 作为上下文的状态信息,裁剪路径不会被清空,所以每次用当前路径更新这个属性,都会导致其叠加当前路径,从而生成新的裁剪路径。
- 对于新生成的路径来说,绘图操作只发生在其内部区域。
- 判断是否属于内部区域时,只能使用
None-Zero Winding Number Rule
。 -
文档对于使用
Even-Odd Fill Rule
的两个方法解释有误
:usesEvenOddFillRule
(UIBezierPath)CGContextEOClip
(CGContextRef)
The function uses the even-odd rule to calculate the intersection of the current path with the current clipping path. Quartz then uses the path resulting from the intersection as the new current clipping path for subsequent painting operations.
正确解释
:在当前路径的子路径之间依照Even-Odd Fill Rule
进行裁剪;再将得到的路径按照None-Zero Winding Number Rule
同当前Clipping Path
进行裁剪;从而得到的新的裁剪路径
。
-
一个综合裁剪和路径绘制的例子:
/**
点击屏幕,图片被添加一圈圆形边框,并存入用户相册
*/
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 计算半径和圆心
CGFloat fullRadius = self.imageView.bounds.size.width * 0.5;
CGPoint center = CGPointMake(CGRectGetMidX(self.imageView.bounds), CGRectGetMidY(self.imageView.bounds));
// 获取原始图片
UIImage *img = [UIImage imageNamed:@"bus-ticket"];
// 开启一个位图上下文
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
/**
1. 绘制圆形边框
2. 添加裁剪路径,紧贴圆形边框内部
3. 绘制图像,可以依照圆形边框的矩形,也可以依照裁剪路径的矩形
*/
// 绘制边框
UIBezierPath *outside = [UIBezierPath bezierPathWithArcCenter:center radius:fullRadius - 5 startAngle:0 endAngle:2 * M_PI clockwise:YES];
outside.lineWidth = 10;
[outside stroke];
// 裁剪路径
UIBezierPath *clip = [UIBezierPath bezierPathWithArcCenter:center radius:fullRadius - 10 startAngle:0 endAngle:2 * M_PI clockwise:YES];
[clip addClip];
// 绘制图片
[img drawInRect:CGRectMake(10, 10, self.imageView.bounds.size.width - 20, self.imageView.bounds.size.height - 20)];
// 获取图片
img = UIGraphicsGetImageFromCurrentImageContext();
self.imageView.image = img;
/**
将图像存入用户相册
*/
UIImageWriteToSavedPhotosAlbum(img, NULL, NULL, NULL);
}