標籤:blog http io ar color os sp for on
- (void)drawRect:(CGRect)rect { //獲得當前上下文 CGContextRef ctx=UIGraphicsGetCurrentContext(); //把當前上下文狀態儲存在棧中 CGContextSaveGState(ctx); //縮放、移動處理(需要放在畫圖之前進行設定) CGContextScaleCTM(ctx, 0.5, 0.5); CGContextTranslateCTM(ctx, 100, 100); CGContextRotateCTM(ctx, M_PI_4); //描點 CGContextMoveToPoint(ctx, 10, 10); CGContextAddLineToPoint(ctx, 100, 100); CGContextAddLineToPoint(ctx, 150, 50); //以下兩種方式均可閉環 //CGContextAddLineToPoint(ctx, 10, 10); CGContextClosePath(ctx); //渲染繪圖,實心和空心 CGContextStrokePath(ctx); //CGContextFillPath(ctx); //把當前上下文狀態儲存在棧中 CGContextSaveGState(ctx); //畫正方形 CGContextAddRect(ctx, CGRectMake(100, 100, 50, 50)); //設定線寬(一定要在CGContextStrokePath之前) //因為之前有過一次渲染繪圖,所以這個屬性設定不影響上面的那個三角形,以下顏色設定同理 //所以,如果想分別設定兩個或多個圖形的屬性,就分別渲染繪圖一次 CGContextSetLineWidth(ctx, 10); //設定顏色(同理,屬性設定的代碼都要在繪圖的代碼之前) CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1); CGContextStrokePath(ctx); //設定樣式 CGContextMoveToPoint(ctx, 20, 160); CGContextAddLineToPoint(ctx, 200, 280); CGContextAddLineToPoint(ctx, 250, 200); CGContextSetLineWidth(ctx, 20); //設定頭尾樣式 CGContextSetLineCap(ctx, kCGLineCapRound); //設定轉角樣式 CGContextSetLineJoin(ctx, kCGLineJoinRound); CGContextStrokePath(ctx); //把儲存在棧中的上下文狀態取出來,恢複。上面那段代碼設定的樣式不會影響其他 CGContextRestoreGState(ctx); //畫橢圓 CGContextAddEllipseInRect(ctx, CGRectMake(200, 130, 60, 30)); //以下等價 //CGContextStrokePath(ctx); CGContextDrawPath(ctx, kCGPathStroke); //畫圓形 CGContextAddEllipseInRect(ctx, CGRectMake(140, 170, 50, 50)); CGContextSetLineWidth(ctx, 3); CGContextStrokePath(ctx); //畫圓弧 CGContextAddArc(ctx, 200, 50, 50, M_PI_4, M_PI, 1); CGContextStrokePath(ctx); //畫1/4圓,以及顏色的設定新方法 CGContextMoveToPoint(ctx, 10, 230); CGContextAddLineToPoint(ctx, 10, 280); CGContextAddLineToPoint(ctx, 60, 280); CGContextAddArc(ctx, 10, 280, 50, 0, -M_PI_2, 1); [[UIColor greenColor] setStroke]; CGContextStrokePath(ctx); //畫圖片和文字(不需要手動取得上下文) NSString *[email protected]"辛丑年一空作"; [str1 drawAtPoint:CGPointZero withAttributes:nil]; UIImage *img=[UIImage imageNamed:@"001"]; [img drawAtPoint:CGPointMake(10, 10)]; //在一個框框裡重疊圖片並署名 CGRect rect1=CGRectMake(50, 50, 100, 100); [img drawAsPatternInRect:rect1]; NSMutableDictionary *attr=[[NSMutableDictionary alloc]init]; attr[NSForegroundColorAttributeName]=[UIColor whiteColor]; attr[NSFontAttributeName]=[UIFont systemFontOfSize:13]; [str1 drawInRect:CGRectMake(50, 140, 100, 100) withAttributes:attr]; //把儲存在棧中的上下文狀態取出來,恢複。上面那段代碼設定的樣式不會影響其他 CGContextRestoreGState(ctx); //裁剪圓形頭像 CGContextAddEllipseInRect(ctx, CGRectMake(150, 150, 100 , 100)); //按照圓形剪裁出一個上下文地區,以後的內容就填充在這個圓形上下文中 CGContextClip(ctx); UIImage *img1=[UIImage imageNamed:@"me"]; [img1 drawAtPoint:CGPointMake(150, 150)];}
【iOS開發-80】Quartz2D繪圖簡介:直線/圓形/橢圓/方形以及上下文棧管理CGContextSaveGState/CGContextRestoreGState