来来来,好玩的东西终于来了。接下来的几篇,咱们都将要聊一聊iOS中绘制图像的事儿哈。之前有一篇说到cell分割线顶头的方法中,有童鞋留言说还可以自己绘制。咳咳,会了绘图这个就不是难事儿啦~
还有很多App里面超炫的特效,其实也都是基于各种绘图、路径哒。来吧,骚年~让我们浪起来。
注意: Quartz 2D 是苹果官方的二维绘图引擎,同时支持 iOS 和 Mac OS X 系统。 Cocos2D(Cocos2D-x、Cocos2D-iPhone、Cocos2D-HTML5等), Cocos2D 是一个第三方开源的2D游戏框架。做2D 游戏的 还有 Sprite Kit。 一般3D 游戏用 unity3D。
因为在drawRect:方法中才能取得跟view相关联的context
当view第一次显示到屏幕上时(加到UIWindow上显示出来) 重绘的时候:调用view的
setNeedsDisplay
或者setNeedsDisplayInRect:
时
drawRect:(CGRect)rect
中的rect指的就是绘图view的bounds- (void)drawRect:(CGRect)rect {
//1.获取图形上下文对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.创建路径
CGMutablePathRef pathM = CGPathCreateMutable();
//设置起点
CGPathMoveToPoint(pathM, NULL, 50, 50);
//加线
CGPathAddLineToPoint(pathM, NULL, 200, 200);
// 把路径添加到图形上下文中
CGContextAddPath(ctx, pathM);
//3.渲染
CGContextStrokePath(ctx);
//释放内存
// CGPathRelease(pathM);
CFRelease(pathM);
}
内存泄漏的静态分析工具
使用Path对象的时候,一定要注意内存的问题,一定要注意内存释放。
好了,坐好了,老司机开始开车啦~
- (void)drawRect:(CGRect)rect {
// 获取context
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 创建起点
CGContextMoveToPoint(ctx, 10, 10);
// 创建两条线段的终点
CGContextAddLineToPoint(ctx, 10, 90);
CGContextAddLineToPoint(ctx, 90, 90);
// 闭合path,让他自动回到原点
CGContextClosePath(ctx);
// 执行渲染
CGContextStrokePath(ctx);
}
- (void)drawRect:(CGRect)rect {
// Drawing code
// 获取context对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加路径
CGContextAddRect(ctx, CGRectMake(10, 10, 50, 50));
// 执行渲染
CGContextStrokePath(ctx);
}
- (void)drawRect:(CGRect)rect {
// 获取context
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加椭圆,通过矩形的方式。给出矩形的起点坐标,长宽,绘制一个内切椭圆
CGContextAddEllipseInRect(ctx, CGRectMake(10, 10, 80, 50));
// 渲染
CGContextStrokePath(ctx);
}
- (void)drawRect:(CGRect)rect {
// 获取context
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 绘制扇形。参数:1+2,圆点坐标。参数3+4,起点和终点的弧度。参数5:0表示顺时针,1表示逆时针。
CGContextAddArc(ctx, 50, 50, 20, M_PI_4, M_PI, 1);
// 渲染
CGContextStrokePath(ctx);
}
- (void)drawRect:(CGRect)rect {
// 获取context
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 绘制扇形。参数:1+2,圆点坐标。参数3+4,起点和终点的弧度。参数5:0表示顺时针,1表示逆时针。
CGContextAddArc(ctx, 50, 50, 20, M_PI_4, M_PI, 1);
CGContextClosePath(ctx);
// 渲染
CGContextStrokePath(ctx);
}
- (void)drawRect:(CGRect)rect {
// 获取context对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加路径:起点、终点
CGContextMoveToPoint(ctx, 10, 10);
CGContextAddLineToPoint(ctx, 80, 80);
// 执行渲染
CGContextStrokePath(ctx);
}
好了,下车~下一篇要更新一下Quartz2D的渲染模式。