- Core Graphics简介
Core Graphics 是基于C的API,用于绘制图形操作。
作为一个初级开发者,我想很多人和我一样,被这个框无数的API和代码逻辑搞的晕头转向,当需要实现相应功能时又感到无从下手,最近项目需要,所以借此机会,自己学习一下,扫描一个技术盲区,写成博客希望对和我一样的选手有所帮助。
demo源码地址 传送
使用Core Graphics 绘制图形,需要首先获得图形上下文(Context),就是需要在哪里绘制,开发中一班都是在View的drawRect方法中获得,Core Graphics的图形上下文(Context)是堆栈式的,只能在栈顶的上下文上画图。为了使用Core Graphics来绘图,最简单的方法就是自定义一个类继承自UIView,并重写子类的drawRect方法。在这个方法中绘制图形。Core Graphics必须要一个图形上下文,才能把东西画在这个画布上。在drawRect方法方法中,我们可以直接获取当前栈顶的上下文(Context)。下面的代码演示了具体操作步骤:
- (void)drawRect:(CGRect)rect { //注意这个方法UIGraphicsGetCurrentContext,在其他的方使用获得的content可能会为nil CGContextRef ref = UIGraphicsGetCurrentContext(); }
俗话说万事开头难,获得图形上下文,我们就成功了一半,接下来我们就考虑需要在上下文上绘制什么东西?
//绘制直线 - (void) drawLine:(CGContextRef) content { //创建一条路径 CGMutablePathRef path = CGPathCreateMutable(); CGContextSetLineWidth(content, 2); CGPathMoveToPoint(path, nil, 10, 10); CGPathAddLineToPoint(path, nil, 200, 200); //把路径添加到上下文,并进行渲染 CGContextAddPath(content, path); CGContextStrokePath(content); //内存管理,凡是Create、Copy、Retain方法创建出来的的值,都必须手动释放。 CGPathRelease(path); } //绘制矩形 - (void) drawCustomRect:(CGContextRef) content { //绘制矩形的方很多 CGContextAddRect(content, CGRectMake(20, 30, 40, 50)); CGContextStrokePath(content); } //绘制圆形 - (void) drawCircle:(CGContextRef) content { //参数的意义 //x,y,半径,开始角度,结束角度,1逆时针,0顺时针 CGContextAddArc(content, 50, 50, 50, -M_PI, M_PI, 1); // CGContextFillPath(content); CGContextStrokePath(content); } //绘制圆弧 - (void) drawArc:(CGContextRef) content { //参数的意义 //x,y,半径,开始角度,结束角度,1逆时针,0顺时针 CGContextAddArc(content, 150, 150, 50, M_PI_4, M_PI_2, 0); CGContextStrokePath(content); } //绘制贝赛尔曲线 - (void) drawBezier:(CGContextRef) content { CGContextBeginPath(content); //draw to this point CGContextMoveToPoint(content, 200.0, 10.0); //draw 贝塞尔曲线 CGContextAddQuadCurveToPoint(content, 15, 220, 150, 200); CGContextStrokePath(content); } //绘制图片 - (void) drawImage:(CGContextRef) content { UIImage *img = [UIImage imageNamed:@"test.jpg"]; [img drawInRect:CGRectMake(100, 200, 100, 100)]; } //绘制文字 - (void) drawText:(CGContextRef) content { NSMutableDictionary *attributes = [NSMutableDictionary dictionary]; attributes[NSFontAttributeName] = [UIFont systemFontOfSize:17]; attributes[NSForegroundColorAttributeName] = [UIColor blueColor]; NSAttributedString *text = [[NSAttributedString alloc]initWithString:@"我是测试的" attributes:attributes]; [text drawAtPoint:CGPointMake(100, 50)]; }
官网demo
介绍Core Graphics的博客
http://www.cocoachina.com/industry/20140115/7703.html