iOS高级-QuartzCore框架-图形上下文栈、矩阵操作、裁剪、重绘(刷帧)

一、图形上下文栈
1.自定义一个MJView,将默认View的Class设置为MJView
2.实现drawRect:方法

-(void)drawRect:(CGRect)rect
{
//1.获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();

//将当前的ctx拷贝一份放到栈中
CGContextSaveGState(ctx);

//设置绘图状态
CGContextSetLineWidth(ctx,10); 
[[UIColor redColor] set];
CGContextSetLineCap(ctx,kCGLineCapRound);

//第1根线
CGContextMoveToPoint(ctx,50,,50);
CGContextAddLineToPoint(ctx,120,190);
CGContextStrokePath(ctx);

//将栈顶的上下文出栈,替换当前的上下文(所以状态回到最初了)
CGContextRestoreGState(ctx);

//第2根线
CGContextMoveToPoint(ctx,200,,70);
CGContextAddLineToPoint(ctx,220,290); 
CGContextStrokePath(ctx);
}

 

二、矩阵操作
1.自定义一个MJView,拖一个View,将Class设置为MJView
2.实现drawRect:方法

-(void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();

//矩阵操作
CGContextRotateCTM(ctx,M_PI_4);
CGContextScaleCTM(ctx,0.5,,0.5); 
CGContextTranslateCTM(ctx,0,50);

CGContextAddRect(ctx,CGRectMake(10,10,50,50));

CGContextAddEllipseInRect(ctx,CGRectMake(100,100,100,100));

CGContextMoveToPoint(ctx,100,100);
CGContextAddLineToPoint(ctx,200,200);

CGContextStrokePath(ctx);
}

 

三、裁剪
裁剪原理:先确定需要裁剪的大小,然后将图片放上去,超过范围的部分都不显示
1.自定义一个MJClipView,将默认View的Class设置为MJClipView
2.实现drawRect:方法

-(void)drawRect:(CGRect)rect
{
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  //1.画圆
  CGContextAddEllipseInRect(ctx,CGRectMake(100,10050,50));
  //2.裁剪
  CGContextClip(ctx);
  CGContextFillPath(ctx);
  //3.显示图片
  UIImage *image = [UIImage imageNamed:@"me"];
  [image drawAtPoint:CGPointMake(100,100)];
}

四、重绘(刷帧)
1.自定义一个MJView,拖一个View,将Class设置为MJView。添加一条属性,为圆的半径。
2.添加View属性,然后拖一个滑动条并监听(Action)
3.实现drawRect:方法

//默认只会在第一次显示View的时候调用(只能由系统自动调用,不能手动调用)
-(void)drawRect:(CGRect)rect
{
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  CGContextAddArc(ctx,125,125,self.radius,0,M_PI * 20);
  CGContextFillPath(ctx);
}

4.在MJView.m中重写setter方法(这样通过点语法可以直接绘制)

-(void)setRadius:(float)radius
{
  _radius = radius;
  //重绘(这个方法内部会重新调用drawRect:方法进行绘制)
  [self setNeedsDisplay];
}

5.实现滑动条的方法

-(IBAction)sizeChange:(UISlider *)sender
{ self.cirecleView.radius
= sender.value; }

 

posted on 2015-08-21 18:43  Marshall_Yin  阅读(376)  评论(0编辑  收藏  举报