您的位置:首页 > 移动开发 > IOS开发

iOS CGContextRef使用简要教程

2015-06-30 17:39 543 查看
Graphics Context是图形上下文,也可以理解为一块画布,我们可以在上面进行绘画操作,绘制完成后,将画布放到我们的view中显示即可,view看作是一个画框.

CGContextRef功能强大,我们借助它可以画各种图形。开发过程中灵活运用这些技巧,可以帮助我们提供代码水平。

说到画图,我就立马想到:我的数学公式都快忘完了。

1.写文字

- (void)drawRect:(CGRect)rect { //获得当前画板 CGContextRef ctx = UIGraphicsGetCurrentContext(); //颜色 CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0); //画线的宽度 CGContextSetLineWidth(ctx, 0.25); //开始写字 [@"我是文字" drawInRect:CGRectMake(10, 10, 100, 30) withFont:font]; [super drawRect:rect]; }

2.画直线

- (void)drawRect:(CGRect)rect { //获得当前画板 CGContextRef ctx = UIGraphicsGetCurrentContext(); //颜色 CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0); //画线的宽度 CGContextSetLineWidth(ctx, 0.25); //顶部横线 CGContextMoveToPoint(ctx, 0, 10); CGContextAddLineToPoint(ctx, self.bounds.size.width, 10); CGContextStrokePath(ctx); [super drawRect:rect]; }

3.画圆

- (void)drawRect:(CGRect)rect { //获得当前画板 CGContextRef ctx = UIGraphicsGetCurrentContext(); //颜色 CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0); //画线的宽度 CGContextSetLineWidth(ctx, 0.25); //void CGContextAddArc(CGContextRef c,CGFloat x, CGFloat y,CGFloat radius,CGFloat startAngle,CGFloat endAngle, int clockwise)1弧度=180°/π (≈57.3°) 度=弧度×180°/π 360°=360×π/180 =2π 弧度 // x,y为圆点坐标,radius半径,startAngle为开始的弧度,endAngle为 结束的弧度,clockwise 0为顺时针,1为逆时针。 CGContextAddArc(ctx, 100, 20, 20, 0, 2*M_PI, 0); //添加一个圆 CGContextDrawPath(ctx, kCGPathStroke); //绘制路径 [super drawRect:rect]; }

4.画矩形

- (void)drawRect:(CGRect)rect { //获得当前画板 CGContextRef ctx = UIGraphicsGetCurrentContext(); //颜色 CGContextSetRGBStrokeColor(ctx, 0.2, 0.2, 0.2, 1.0); //画线的宽度 CGContextSetLineWidth(ctx, 0.25); CGContextAddRect(ctx, CGRectMake(2, 2, 30, 30)); CGContextStrokePath(ctx); [super drawRect:rect]; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: