IOS-Core Graphic 畫圖
*重新定義UIView 並在drawRect:(CGRect) rect;中繪製
1.繪製路徑
_context=UIGraphicsGetCurrentContext(); CGMutablePathRef path=CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 50, 50); CGPathAddLineToPoint(path, NULL, 150, 150); CGPathAddLineToPoint(path, NULL, 50, 150); CGPathCloseSubpath(path); CGContextAddPath(_context, path); CGFloat myColor[4]={1.0f,1.0f,0,1.0f}; CGContextSetFillColor(_context,myColor); CGContextSetStrokeColor(_context, myColor); CGContextSetShouldAntialias(_context, NO); CGContextSetLineWidth(_context, 15.0); CGContextSetLineJoin(_context, kCGLineJoinRound); CGContextDrawPath(_context, kCGPathStroke); CGPathRelease(path); CGContextRelease(_context);
2.繪製矩形
CGRect rect2=CGRectMake(0, 0, 200, 200); CGContextSetStrokeColorWithColor(_context, [UIColor redColor].CGColor); CGContextSetLineWidth(_context, 2.0); CGContextStrokeRect(_context, rect2);
3.繪製漸層
_context=UIGraphicsGetCurrentContext(); //顏色模式 CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB(); //構建顏色值 NSArray *colors=@[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor greenColor].CGColor]; //顏色點的位置 CGFloat location[2]={0,1}; //設定漸層模式 CGGradientRef gradient=CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors,location); CGContextSaveGState(_context); CGRect rect2=CGRectMake(0, 0, 150, 150); //繪製地區 CGContextAddRect(_context, rect2); //地區裁剪 CGContextClip(_context); //裁剪位置 CGContextDrawLinearGradient(_context, gradient, CGPointMake(0, 0), CGPointMake(150, 150),kCGGradientDrawsAfterEndLocation); CGContextRestoreGState(_context); //釋放資源 CGColorSpaceRelease(colorSpace); CGGradientRelease(gradient); CGContextRelease(_context);
4.繪製文字
NSString *str=[UIFont fontWithName:@"Gill Sans" size:30]; NSString *drawText=@"hello !"; [drawText drawAtPoint:CGPointMake(30, 100) withFont:str];
5.繪製圖片
UIImage *image=[UIImage imageNamed:@"頭像2.png"]; [image drawAtPoint:CGPointMake(30, 30)]; CGImageRelease([image CGImage]);
6.貝茲路徑繪製
//繪製線 UIBezierPath *path=[UIBezierPath bezierPath]; [path moveToPoint:CGPointMake(30, 30)]; [path addLineToPoint:CGPointMake(30, 120)]; [path addLineToPoint:CGPointMake(120, 120)]; [path closePath]; //繪製圓 UIBezierPath *path=[UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:100.0 startAngle:0 endAngle:180 clockwise:YES]; //繪製矩形 UIBezierPath *path=[UIBezierPath bezierPathWithRect:CGRectMake(20, 20, 150, 150)]; //繪製橢圓 UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(10, 10, 120, 60)]; //設定顏色 [[UIColor redColor]set]; path.lineWidth=5; [path fill]; [[UIColor yellowColor]set]; [path stroke];
7.儲存繪製環境,在繪製過程中 屬性可能需要儲存到棧中 這時候調用CGContextSaveGState進行儲存,
並在需要的時候通過CGContextRestoreGState進行恢複。