---
title: "CGContextRef用法"
author: "bydshine"
date: "2013-04-11T10:12:28Z"
tags: []
categories: ["移动开发"]
slug: "cgcontextref"
draft: false
lastmod: "2013-04-11T10:12:28Z"
id: 1845522
url: "https://bydshine.iteye.com/blog/1845522"
---

quartz 是主要的描画接口，支持基于路径的描画、
抗锯齿渲染、渐变填充模式、图像、颜色、坐标空间变换、以及PDF 文档的创建、显示、和分析。UIKit 为Quartz 的图像和颜色操作提供了Objective-C 的封装。Core Animation 为很多UIKit 的视图属性声明的动画效果提供底层支持，也可以用于实现定制的动画。
在调用您提供的drawRect:方法之前，视图对象会自动配置其描画环境，使您的代码可以立即进行描画。作为这些配置的一部分，UIView 对象会为当前描画环境创建一个图形上下文（对应于CGContextRef 封装类型）
用户坐标空间是您发出的所有描画命令的工作环境。该空间的单位由点来表示。设备坐标空间指的是设备内在的坐标空间，由像素来表示。缺省情况下，用户坐标空间上的一个点等于设备坐标空间的一个像素，这意味着一个点等于1/160英寸。然而，您不应该假定这个比例总是1:1。
UIColor 对象提供了一些便利方法，用于通过RGB、HSB、和灰度值指定颜色值。
您也可以使用Core Graphics 框架中的CGContextSetRGBStrokeColor 和
CGContextSetRGBFillColor 函数来创建和设置颜色。
路径轮廓可以用像CGContextStrokePath 这样的函数来画，即用当前的笔划颜色画出以路径为中心位置的线。路径的填充则可以用CGContextFillPath 函数来实现，它的功能是用当前的填充颜色或样式填充路径线段包围的区域。
获取上下文，图形上下文是什么意思？
CGContextRef context = UIGraphicsGetCurrentContext();
 
画一个正方形图形 没有边框
CGContextSetRGBFillColor(context, 0, 0.25, 0, 0.5);
CGContextFillRect(context, CGRectMake(2, 2, 270, 270));
CGContextStrokePath(context);
 
写文字
CGContextSetLineWidth(context, 1.0);
CGContextSetRGBFillColor (context,  1, 1, 1, 1.0);
UIFont  *font = [UIFont boldSystemFontOfSize:11.0];
[@"fangyp" drawInRect:CGRectMake(40, 40, 80, 20) withFont:font];
 
画一条线
CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 0.5);//线条颜色
CGContextMoveToPoint(context, 20, 20);
CGContextAddLineToPoint(context, 200,20);
CGContextStrokePath(context);
 
画正方形边框
CGContextSetRGBStrokeColor(context, 1, 1.0, 1.0, 1.0); 
CGContextSetLineWidth(context, 2.0);
CGContextAddRect(context, CGRectMake(2, 2, 270, 270));
CGContextStrokePath(context);
 
画方形背景颜色
  CGContextTranslateCTM(ctx, 0.0f, self.view.bounds.size.height);
   CGContextScaleCTM(ctx, 1.0f, -1.0f);
   UIGraphicsPushContext(ctx);
  CGContextSetLineWidth(ctx,320);
  CGContextSetRGBStrokeColor(ctx, 250.0/255, 250.0/255, 210.0/255, 1.0); 
  CGContextStrokeRect(ctx, CGRectMake(0, 0, 320, 460));
  UIGraphicsPopContext(); 

1、画线：在uiview类里重写下面方法

-(void)drawRect:(CGRect)rect
{
 
   CGContextRefcontext = UIGraphicsGetCurrentContext();
    
    //画线
//    UIColor*aColor = [UIColor colorWithRed:0 green:1.0 blue:0 alpha:0];
   CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1.0);
//   CGContextSetFillColorWithColor(context, aColor.CGColor);
   CGContextSetLineWidth(context, 4.0);
    CGPointaPoints[5];
    aPoints[0] =CGPointMake(60, 60);
    aPoints[1] =CGPointMake(260, 60);
    aPoints[2] =CGPointMake(260, 300);
    aPoints[3] =CGPointMake(60, 300);
    aPoints[4] =CGPointMake(60, 60);
   CGContextAddLines(context, aPoints, 5);
   CGContextDrawPath(context, kCGPathStroke); //开始画线
    
    //椭圆
    CGRect aRect= CGRectMake(80, 80, 160, 100);
   CGContextSetRGBStrokeColor(context, 0.6, 0.9, 0, 1.0);
   CGContextSetLineWidth(context, 3.0);
//   CGContextSetFillColorWithColor(context, aColor.CGColor);
//   CGContextAddRect(context, rect); //矩形
   CGContextAddEllipseInRect(context, aRect); //椭圆
   CGContextDrawPath(context, kCGPathStroke);
   

2、弧线 CGContextAddArcToPoint与CGContextAddArc

void CGContextAddArc(CGContextRef c,CGFloat x, CGFloat y,CGFloat radius,CGFloat startAngle,CGFloat endAngle, int clockwise)  
x,y为圆点坐标，startAngle为开始的弧度，endAngle为 结束的弧度，clockwise 0为顺时针，1为逆时针。
以下是示例代码。  
CGContextBeginPath(context);  
CGContextSetRGBStrokeColor(context, 0, 1, 0, 1); 
CGContextAddArc(context, 100, 100, 50, 180* PI/ 180, 270* PI/ 180,0);  CGContextStrokePath(context); 

void CGContextAddArcToPoint(CGContextRef c,CGFloat x1, CGFloat y1,CGFloat x2, CGFloat y2,CGFloat radius); 
首先使用该函数绘制圆弧前，首先要确定一个start point.
CGContextMoveToPoint(context, 100, 100);
然后设置CGContextAddArcToPoint(context, 50, 100, 50, 150, 50);
这里是从起始点100,100开始到第一个点50,100画一条线段，然后再从第一个点50,100到第二点150,50画另一条线段（这是两条相交切线），然后设置半径为50.通过相交的两条线段和半径就可以确定圆弧了。
示例代码如下：
CGContextBeginPath(context);
CGContextSetRGBStrokeColor(context, 0, 0, 1, 1);
CGContextMoveToPoint(context, 100, 100);
CGContextAddArcToPoint(context, 50, 100, 50, 150, 50);
CGContextStrokePath(context);
注意：Path被绘制后，当前点的坐标更改为150,50
0  CGContextRef context = UIGraphicsGetCurrentContext(); 设置上下文
1 CGContextMoveToPoint 开始画线
2 CGContextAddLineToPoint 画直线


4 CGContextAddEllipseInRect 画一椭圆
4 CGContextSetLineCap 设置线条终点形状
4 CGContextSetLineDash 画虚线
4 CGContextAddRect 画一方框
4 CGContextStrokeRect 指定矩形
4 CGContextStrokeRectWithWidth 指定矩形线宽度
4 CGContextStrokeLineSegments 一些直线


5 CGContextAddArc 画已曲线 前俩店为中心 中间俩店为起始弧度 最后一数据为0则顺时针画 1则逆时针
5 CGContextAddArcToPoint(context,0,0, 2, 9, 40);//先画俩条线从point 到 弟1点 ， 从弟1点到弟2点的线  切割里面的圆
6 CGContextSetShadowWithColor 设置阴影
7 CGContextSetRGBFillColor 这只填充颜色
7 CGContextSetRGBStrokeColor 画笔颜色设置
7 CGContextSetFillColorSpace 颜色空间填充
7 CGConextSetStrokeColorSpace 颜色空间画笔设置
8 CGContextFillRect 补充当前填充颜色的rect
8 CGContextSetAlaha 透明度


9 CGContextTranslateCTM 改变画布位置
10 CGContextSetLineWidth 设置线的宽度
11 CGContextAddRects 画多个线
12 CGContextAddQuadCurveToPoint 画曲线
13  CGContextStrokePath 开始绘制图片
13 CGContextDrawPath 设置绘制模式
14 CGContextClosePath 封闭当前线路
15 CGContextTranslateCTM(context, 0, rect.size.height);    CGContextScaleCTM(context, 1.0, -1.0);反转画布
16 CGContextSetInterpolationQuality 背景内置颜色质量等级
16 CGImageCreateWithImageInRect 从原图片中取小图


17 字符串的 写入可用  nsstring本身的画图方法 - (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignment)alignment;来写进去即可


18对图片放大缩小的功能就是慢了点 
    UIGraphicsBeginImageContext(newSize);
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();


19 CGColorGetComponents（） 返回颜色的各个直 以及透明度 可用只读const float 来接收  是个数组


20 画图片 CGImageRef image＝CGImageRetain(img.CGImage);
     CGContextDrawImage(context, CGRectMake(10.0, height -              
     100.0, 90.0, 90.0), image);


21 实现逐变颜色填充方法 CGContextClip(context);
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colors[] =
    {
        204.0 / 255.0, 224.0 / 255.0, 244.0 / 255.0, 1.00,
        29.0 / 255.0, 156.0 / 255.0, 215.0 / 255.0, 1.00,
        0.0 / 255.0,  50.0 / 255.0, 126.0 / 255.0, 1.00,
    };
    CGGradientRef gradient = CGGradientCreateWithColorComponents       
   (rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
    CGColorSpaceRelease(rgb);    
    CGContextDrawLinearGradient(context, gradient,CGPointMake    
   (0.0,0.0) ,CGPointMake(0.0,self.frame.size.height),                    
     kCGGradientDrawsBeforeStartLocation);
    
22 注:  画完图后,必须 
    先用CGContextStrokePath来描线,即形状 
    后用CGContextFillPath来填充形状内的颜色. 


填充一个路径的时候，路径里面的子路径都是独立填充的。
假如是重叠的路径，决定一个点是否被填充，有两种规则
1,nonzero winding number rule:非零绕数规则，假如一个点被从左到右跨过，计数器+1，从右到左跨过，计数器-1，最后，如果结果是0，那么不填充，如果是非零，那么填充。
2,even-odd rule: 奇偶规则，假如一个点被跨过，那么+1，最后是奇数，那么要被填充，偶数则不填充，和方向没有关系。


 Function
Description 
 CGContextEOFillPath
 使用奇偶规则填充当前路径
 CGContextFillPath
 使用非零绕数规则填充当前路径
 CGContextFillRect
 填充指定的矩形
 CGContextFillRects
 填充指定的一些矩形
 CGContextFillEllipseInRect
 填充指定矩形中的椭圆
 CGContextDrawPath
 两个参数决定填充规则，kCGPathFill表示用非零绕数规则，kCGPathEOFill表示用奇偶规则，kCGPathFillStroke表示填充，kCGPathEOFillStroke表示描线，不是填充




设置当一个颜色覆盖上另外一个颜色，两个颜色怎么混合
默认方式是
result = (alpha * foreground) + (1 - alpha) * background


CGContextSetBlendMode :设置blend mode.
CGContextSaveGState :保存blend mode.
CGContextRestoreGState:在没有保存之前，用这个函数还原blend mode.
CGContextSetBlendMode 混合俩种颜色
http://www.cocoachina.com/bbs/read.php?tid=75122&page=1