深入理解图形上下文

来源:互联网 发布:简约主义 知乎 编辑:程序博客网 时间:2024/05/16 23:57

UIImage+Extension.swift

 

import UIKit


extension UIImage

{

    // 变图片的颜色

    classfunc 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 = 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

CGContextRef context = UIGraphicsGetCurrentContext(); 设置上下文

CGContextMoveToPoint 开始画线

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 混合俩种颜色



下面是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         // 生成UIImage19         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引擎进行一次绘图操作所需的信息。这些信息可以分为三部分:
    1. 画在哪里?即绘图目标,可以是图层(CALayer),应用窗口(OS X),位图图像PDF文件以及打印机。这部分信息不可修改
    2. 画些什么?即绘图路径,可以是UIBezierPath(OC)或者CGPathRef(C)对象。每次执行绘图操作后,这部分信息被自动清空。
    3. 用什么画?即绘图状态,包括线宽,颜色,样式,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);}

0 0