iOSQuartz2D画图

Quartz2D是一个二维绘图引擎,同时支持iOS和Mac OS X系统(跨平台,纯 C语言的)。

Quartz2D提供了以下几种类型的Graphics Context:

  • Bitmap Graphics Context
  • PDF Graphics Context
  • Window Graphics Context
  • Layer Graphics Context
  • Printer Graphics Context

核心步骤:

获得上下文
绘制/拼接绘图路径
将路径添加到上下文
渲染上下文

常见使用

  • 画线(一条线)
 //方法1.

//1.获取图形上下文
//目前我们所用的上下文都是以UIGraphics
//CGContextRef 引用到的类型和函数都是CG开头,是CoreGraphics框架
CGContextRef cts = UIGraphicsGetCurrentContext();
//2.描述路径
//2.1创建路径
CGMutablePathRef path = CGPathCreateMutable();
//2.2设置起点 path:给哪个路径设置起点 第二个参数是否形变
CGPathMoveToPoint(path, NULL,50,50);
//2.3添加一根线到某个点
CGPathAddLineToPoint(path, NULL,200,200);
//3.把路径添加到上下文
CGContextAddPath(cts,path);
//4.渲染上下文
CGContextStrokePath(cts); 

//方法2

//获取上下文
CGContextRef tes = UIGraphicsGetCurrentContext();
//描述路径
//设置起点
CGContextMoveToPoint(tes,50,50);
CGContextAddLineToPoint(tes,200,200);
//渲染
CGContextStrokePath(tes);


//方法三

//贝塞尔路径
//创建路径
UIBezierPath *path = [UIBezierPath bezierPath];
//设置起点
[path moveToPoint:CGPointMake(50,50)];
//添加一根线到某点
[path addLineToPoint:CGPointMake(200,200)];
//绘制路径
[path stroke];
  • 画线(两条)
//方法1
//获取上下文
CGContextRef cos = UIGraphicsGetCurrentContext();
//绘制路径
CGContextMoveToPoint(cos,50,50);

CGContextAddLineToPoint(cos,100,100);
//默认下一根线的起点就是上一个线的终点(当然如果不想连线的话就在写一个起点)
CGContextAddLineToPoint(cos,100,200);


//设置绘图状态,要在渲染之前
//颜色
[[UIColor redColor] setStroke];
//线宽
CGContextSetLineWidth(cos,10);
//设置连接样式
CGContextSetLineJoin(cos, kCGLineJoinRound);
//设置顶角样式
CGContextSetLineCap(cos,kCGLineCapRound);


//渲染上下文
CGContextStrokePath(cos);


//方法2
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(20,20)];
[path addLineToPoint:CGPointMake(100,100)];
path.lineWidth = 10;
[[UIColor redColor] set];
[path stroke];

UIBezierPath *path1 = [UIBezierPath bezierPath];
[path1 moveToPoint:CGPointMake(80,80)];
[path1 addLineToPoint:CGPointMake(60,100)];
path1.lineWidth = 10;
[[UIColor orangeColor] set];

[path1 stroke];


//方法3
//获取上下文
CGContextRef cos = UIGraphicsGetCurrentContext();
//绘制路径
CGContextMoveToPoint(cos, 80,80);

CGContextAddQuadCurveToPoint(cos, 150,20, 260, 50);
//渲染
CGContextStrokePath(cos);
  • 画柱状图
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(50, 50, 50, 50)];
[path stroke];
  • 画圆
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(20,20,100,100) cornerRadius:50];
[path stroke];
  • 画圆弧
//圆弧Center是圆心  ,startAngle参数是弧度  clockwise参数YES是顺时针NO是逆时针
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:50 startAngle:0 endAngle:M_PI_2 clockwise:YES];
[path stroke];
  • 画扇形
CGPoint center = CGPointMake(100, 100);
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:50 startAngle:0 endAngle:M_PI_2 clockwise:YES];
//添加一根线到圆心
[path addLineToPoint:center];
//封闭路径,从路径的终点到起点
// [path closePath];
//填充,默认关闭路径
[path fill];
  • 画饼图
- (void)drawRect:(CGRect)rect {

  NSArray *arr = [self arrRandom];
  CGFloat radius = rect.size.width*0.5;
  CGPoint center = CGPointMake(radius,radius);
  CGFloat startA = 0;
  CGFloat angle = 0;
  CGFloat endA = 0;

  for (int i =0;i < arr.count;i ++) {
    startA = endA;
    angle = [arr[i] doubleValue]/100.0*M_PI*2;
    endA = startA+angle;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    [path addLineToPoint:center];
    [[self colorRandom] set];
    [path fill];
  }

  }
  - (NSArray*)arrRandom{

  int totoal = 100;
  NSMutableArray *arr = [NSMutableArray array];
  int temp = 0;
  for (int i=0;i <arc4random_uniform(10)+1;i ++) {
    temp = arc4random_uniform(totoal)+1;
    [arr addObject:@(temp)];
    
    //一个100  一次10  二次60 40  三次 30
    if (temp == totoal) {
        break;
    }
    
    totoal -= temp;
  }

  return arr;

  }
  - (UIColor*)colorRandom{

  //0~255  RGB
   //OC 0~1
  CGFloat r = arc4random_uniform(256)/255.0;
  CGFloat g = arc4random_uniform(256)/255.0;
  CGFloat b = arc4random_uniform(256)/255.0;
  return [UIColor colorWithRed:r green:g blue:b alpha:1];
   }
  - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self setNeedsDisplay];
  }
  #pragma mark - 笨的方法
  - (void)draw{

    CGFloat radius = self.bounds.size.width*0.5;
    CGPoint center = CGPointMake(radius,radius);

    CGFloat startA = 0;
     CGFloat angle = 0;
    CGFloat endA = 0;

    //第一个扇形
    angle = 25/100.0 * M_PI * 2;
    endA = startA + angle;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    //添加一条线到圆心
    [path addLineToPoint:center];
    //描边和填充通用
    [[UIColor redColor] set];

    [path fill];

    //第二个扇形
    startA = endA;
    angle = 25/100.0 * M_PI * 2;
    endA = startA + angle;
    UIBezierPath *path1 = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    //添加一条线到圆心
    [path1 addLineToPoint:center];
    //描边和填充通用
    [[UIColor greenColor] set];
    [path1 fill];

    //第三个扇形
    startA = endA;
    angle = 50/100.0 * M_PI * 2;
    endA = startA + angle;
    UIBezierPath *path2 = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    //添加一条线到圆心
    [path2 addLineToPoint:center];
    //描边和填充通用
    [[UIColor blueColor] set];
    [path2 fill];
  }

实际开发常用

  • 图片水印效果
UIImage *img = [UIImage imageNamed:@"Default-667h"];
//0.获取上下文(注意UIGraphicsGetCurrentContext()z在drawRectf方法中)
//开启一个位图上下文 参数1:新图片尺寸  2:不透明度YES不透明通常透明 3:缩放上下文取值0不缩放
UIGraphicsBeginImageContextWithOptions(img.size, NO,0);

//1.绘制原生的图片
[img drawAtPoint:CGPointZero];
//2.给原生的图片添加文字
NSString *str = @"Hello";
[str drawAtPoint:CGPointMake(400,1000) withAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:40]}];

//3.生成一张新的图片 从上下文获取图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//4.关闭上下文
UIGraphicsEndImageContext();

self.imgView.image = newImage;
  • 裁剪图片
//图片宽
CGFloat imgWidth = image.size.width;
//图形的宽度和高度
CGFloat ovalWH = imgWidth + 2 * borderWidth;
//1.开启上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(ovalWH, ovalWH), NO, 0);
//2.画大图
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0,0, ovalWH, ovalWH)];
[[UIColor redColor] set];
[path fill];

//3.设置裁剪区域
UIBezierPath *path1 =[UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderWidth,borderWidth, imgWidth,imgWidth)];
[path1 addClip];

//4.绘制图片
[image drawAtPoint:CGPointMake(borderWidth,borderWidth)];
//5.获取图片
UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
//6.关闭上下文
UIGraphicsEndImageContext();
self.imgView.image = newImage;
  • 屏幕截图
//1.获取位图上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0);     
//2.开启上下文
CGContextRef ref = UIGraphicsGetCurrentContext();

// 3.把控件上的图层渲染到上下文,layer只能渲染
[self.view.layer renderInContext:ref];

//4.生成一张图片
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

//5.关闭上下文
UIGraphicsEndImageContext();
// compressionQuality: 图片质量 1:最高质量
NSData *data = UIImageJPEGRepresentation(img,1);
 //6.将图片写入
[data writeToFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:@"shopDetailAddImg"] atomically:YES];
//7.读取
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"shopDetailAddImg"];
[UIImage imageWithContentsOfFile:path];

补充

drawRect方法

绘图只有实现drawRect:方法才能绘图到view上,因为只有里面可以获取view中layer的上下文。

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

推荐阅读更多精彩内容

  • Quartz2D以及drawRect的重绘机制字数1487 阅读21 评论1 喜欢1一、什么是Quartz2D Q...
    PurpleWind阅读 730评论 0 3
  • 什么是Quartz2D? Quartz 2D是一个二维图形绘制引擎,支持iOS环境和Mac OS X环境。我们可以...
    小番茄阳阳阅读 918评论 0 4
  • 简述: 1、Quartz2D是什么Quartz2D是二维绘图引擎,同时支持IOS和Mac 2、Quartz2D能做...
    LitterL阅读 617评论 0 6
  • 一、什么是Quartz2D Quartz2D是⼀个二维绘图引擎,同时支持iOS和Mac系统Quartz2D的API...
    CoderZb阅读 2,262评论 4 17
  • 什么是Quartz2D 是一个二维的绘图引擎,同时支持iOS和Mac系统 Quartz2D的API是纯C语言的,它...
    Mario_ZJ阅读 549评论 0 1