08-Graphics Context State stack

Source: Internet
Author: User

08-Graphics Context State stack

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

Code implementation:

#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

Implementation results:

Matrix Operations for contexts

 上下文的矩阵操作其实就是修改上下文的形变,  主要有以下几种  平移  CGContextTranslateCTM(ctx, 100, 100);  旋转  CGContextRotateCTM(ctx, M_2_PI);  缩放  CGContextScaleCTM(ctx, 0.5, 0.5);  注意:上下文操作必须得要在添加路径之前去设置

08-Graphics Context State stack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.