zoukankan      html  css  js  c++  java
  • 08

    08-图形上下文状态栈

    上下文状态栈为内存中的一块区域,它用来保存前上下文当的状态.
    我们获取的图层上下文当中其实两块区域,一个是存放添加的路径,一个是用来保存用户设置的状态,
    这些状态包括线条的颜色,线宽等.
    当我们把上下文的内容渲染到View上面的时候, 
    它会自动将设置的所有上下文状态运行到保存的路径上面显示到View上面.
    
    如果想要有多种状态,可以先把路径渲染到View上面,
    再从新添加路径.添加完路径之后,重新设置上下文的状态.
    再把新设置的上下文状态渲染到View上面.
    
    我们可以利用上下文状态栈的方式,在设置状态之前,把之前的状态保存到上下文状态栈里面.
    下一次想要再使用之前的状态时, 可以从上下文状态当中取出之前保存的上下文状态.
    
    1.如何把上下文状态保存到上下文状态栈?
       CGContextSaveGState(ctx);
    2.如何从上下文状态栈中取出上下文状态?
       CGContextRestoreGState(ctx);

    代码实现:

    
    #import "ZYQView.h"
    
    @implementation ZYQView
    
    
    - (void)drawRect:(CGRect)rect {
        // 第一条线
        //获取上下文
        CGContextRef ctr = UIGraphicsGetCurrentContext();
        //获取路径
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(40, 100)];
        [path addLineToPoint:CGPointMake(180, 100)];
        //保存当前上下文的状态设置
        CGContextSaveGState(ctr);
        //设置上下文的状态
        CGContextSetLineWidth(ctr, 10);
        [[UIColor blueColor] set];
        //将路径添加到上下文中
        CGContextAddPath(ctr, path.CGPath);
        //渲染上下文
        CGContextStrokePath(ctr);
        
        //第二条线
        path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(110, 50)];
        [path addLineToPoint:CGPointMake(110, 150)];
        
        //从上下文状态栈当中取出保存状态
        CGContextRestoreGState(ctr);
        //将路径添加到上下文中
        CGContextAddPath(ctr, path.CGPath);
        //渲染上下文
        CGContextStrokePath(ctr);    
    }
    @end
    

    实现效果:

    上下文的矩阵操作

     上下文的矩阵操作其实就是修改上下文的形变,
      主要有以下几种
      平移
      CGContextTranslateCTM(ctx, 100, 100);
      旋转
      CGContextRotateCTM(ctx, M_2_PI);
      缩放
      CGContextScaleCTM(ctx, 0.5, 0.5);
      注意:上下文操作必须得要在添加路径之前去设置
  • 相关阅读:
    pat 甲级 1065. A+B and C (64bit) (20)
    pat 甲级 1064. Complete Binary Search Tree (30)
    pat 甲级 1010. Radix (25)
    pat 甲级 1009. Product of Polynomials (25)
    pat 甲级 1056. Mice and Rice (25)
    pat 甲级 1078. Hashing (25)
    pat 甲级 1080. Graduate Admission (30)
    pat 甲级 团体天梯 L3-004. 肿瘤诊断
    pat 甲级 1099. Build A Binary Search Tree (30)
    Codeforce 672B. Different is Good
  • 原文地址:https://www.cnblogs.com/zhoudaquan/p/5034477.html
Copyright © 2011-2022 走看看