美文网首页
CGContextSaveGState和CGContextRes

CGContextSaveGState和CGContextRes

作者: hello_iOS程序媛 | 来源:发表于2018-03-12 18:59 被阅读0次

使用Quartz时涉及到一个图形上下文,其中图形上下文中包含一个保存过的图形状态堆栈。在Quartz创建图形上下文时,该堆栈是空的。[CGContextSaveGState]函数的作用是将当前图形状态推入堆栈。之后,您对图形状态所做的修改会影响随后的描画操作,但不影响存储在堆栈中的拷贝。在修改完成后,您可以通过[CGContextRestoreGState]函数把堆栈顶部的状态弹出,返回到之前的图形状态。这种推入和弹出的方式是回到之前图形状态的快速方法,避免逐个撤消所有的状态修改;这也是将某些状态(比如裁剪路径)恢复到原有设置的唯一方式。

    CGRect targetRect = CGRectMake(0, 0, 400, 400);
    UIGraphicsBeginImageContextWithOptions(targetRect.size, YES, 0.0);  //生成Image上下文
    CGContextRef context = UIGraphicsGetCurrentContext(); //获取当前上下文
    
    CGFloat myFillColor[] = {1,0,0,1}; //red;
    CGContextSaveGState(context);  //保存图形上下文状态
    
    CGContextSetRGBFillColor(context, 0,1,1,1);  //设置图形上下文当前的填充颜色空间为DeviceRGB和设置填充颜色的red、green、blue、alpha
    CGContextFillRect(context, targetRect);  //用当前颜色填充targetRect区域
    CGContextSetFillColor(context, myFillColor);  //设置当前填充颜色的值为myFillColor
    CGContextFillEllipseInRect(context, targetRect); //用当前颜色填充在targetRect的椭圆
    CGContextFillPath(context);
    CGContextRestoreGState(context);
    
    UIImage *uiImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

上述代码生成的image效果如下图所示:


image显示效果
// UIImage 上下文
//以下方法只会在DeviceRGB色彩空间中返回每个通道8位的上下文
//鼓励任何新的位图绘图代码使用UIGraphicsImageRenderer (ios 10.0)
UIKIT_EXTERN void     UIGraphicsBeginImageContext(CGSize size);  //生成UIImage 上下文 scale默认为1.0
UIKIT_EXTERN void     UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) NS_AVAILABLE_IOS(4_0);  //生成UIImage 上下文
UIKIT_EXTERN UIImage* __nullable UIGraphicsGetImageFromCurrentImageContext(void);  //从当前Image上下文中获取图片
UIKIT_EXTERN void     UIGraphicsEndImageContext(void);  //从栈中移除该图形上下文

相关文章

网友评论

      本文标题:CGContextSaveGState和CGContextRes

      本文链接:https://www.haomeiwen.com/subject/azkofftx.html