iOS CGContextRef使用简要教程

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]; }

 

转载于:https://www.cnblogs.com/tongyuling/p/4611175.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值