from : http://www.cnblogs.com/qingjoin/archive/2013/09/24/3337488.html
UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 100, 320, 20)]; [self.view addSubview:imageView1]; UIGraphicsBeginImageContext(imageView1.frame.size); //开始画线 [imageView1.image drawInRect:CGRectMake(0, 0, imageView1.frame.size.width, imageView1.frame.size.height)]; CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); //设置线条终点形状 float lengths[] = {10,5}; CGContextRef line = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(line, [UIColor redColor].CGColor); CGContextSetLineDash(line, 0, lengths, 2); //画虚线 CGContextMoveToPoint(line, 0.0, 20.0); //开始画线 CGContextAddLineToPoint(line, 310.0, 20.0); CGContextStrokePath(line); imageView1.image = UIGraphicsGetImageFromCurrentImageContext();
from : http://blog.youkuaiyun.com/zhangao0086/article/details/7234859
画虚线需要用到函数:
CGContextSetLineDash
此函数需要四个参数:
- context – 这个不用多说
- phase - 稍后再说
- lengths – 指明虚线是如何交替绘制,具体看例子
- count – lengths数组的长度
lengths的值{10,10}表示先绘制10个点,再跳过10个点,如此反复,如图:
如果把lengths值改为{10, 20, 10},则表示先绘制10个点,跳过20个点,绘制10个点,跳过10个点,再绘制20个点,如此反复,如图:
注意count的值等于lengths数组的长度
phase参数表示在第一个虚线绘制的时候跳过多少个点,举例说明:
如图显示:
由于lengths值为{10,5},第一条线就是绘制10,跳过5,反复绘制。
第二条线的phase值为5,则首先绘制【10减去5】,再跳过5,绘制10,反复绘制。
第三条给也如此,先绘制2,再跳过5,如此反复。