最简单的画线功能
转载自:http://www.codeios.com/thread-863-1-1.html
示例非常简单。
首先要有个UIImageView,在本例中声明为成员变量:
@interface PathDemoViewController : UIViewController {
UIImageView *imageView;
}
画线的代码:
//图片视图控件初始化
imageView=[[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
//设置背景色
imageView.backgroundColor=[UIColor cyanColor];
//加入到当前视图
[self.view addSubview:imageView];
//设置当前视图背景色
self.view.backgroundColor=[UIColor yellowColor];
//开始图片处理并得到上下文:图片处理区域为imageView控件范围
UIGraphicsBeginImageContext(imageView.frame.size);
//获得处理的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//设置线条样式
CGContextSetLineCap(context, kCGLineCapSquare);
//设置线条粗细宽度
CGContextSetLineWidth(context, 2.0);
CGContextSetAllowsAntialiasing(context, YES);
//设置颜色
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
//开始一个起始路径
CGContextBeginPath(context);
//起始点设置为(40,40):注意这是上下文对应区域中的相对坐标,
//也就是上面imageView定义的(50,50,200,200)区域中的相对位置
CGContextMoveToPoint(context, 40, 40);
//重新开始一个起始路径:前面的起始路径作废
CGContextBeginPath(context);
//起始点设置为(0,0):注意这是上下文对应区域中的相对坐标,
//也就是上面imageView定义的(50,50,200,200)区域中的相对位置
CGContextMoveToPoint(context, 0, 0);
//设置下一个坐标点
CGContextAddLineToPoint(context, 100, 100);
//设置下一个坐标点
CGContextAddLineToPoint(context, 20, 150);
//设置下一个坐标点
CGContextAddLineToPoint(context, 50, 180);
//连接上面定义的坐标点
CGContextStrokePath(context);
//将上下文内容赋给imageView控件
imageView.image=UIGraphicsGetImageFromCurrentImageContext();
//结束图片处理上下文:对应于前面的UIGraphicsBeginImageContext
UIGraphicsEndImageContext();
其中:
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
设置了线的边缘样式: