*重新定義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);
CGRect rect2=CGRectMake(0, 0, 200, 200); CGContextSetStrokeColorWithColor(_context, [UIColor redColor].CGColor); CGContextSetLineWidth(_context, 2.0); CGContextStrokeRect(_context, rect2);
_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);
NSString *str=[UIFont fontWithName:@"Gill Sans" size:30]; NSString *drawText=@"hello !"; [drawText drawAtPoint:CGPointMake(30, 100) withFont:str];
UIImage *image=[UIImage imageNamed:@"頭像2.png"]; [image drawAtPoint:CGPointMake(30, 30)]; CGImageRelease([image CGImage]);
//繪制線 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];
並在需要的時候通過CGContextRestoreGState進行恢復。