很多控件中希望加一条线, 常见横的竖的, 比如在一个页面的header里, cell中, 像tableview那样那样的分割线.
所以我总结了几种方式供大家参考:
1. 利用CGContext去画, 举个例子:
- UIImageView *imageView=[[UIImageView alloc] initWithFrame:self.view.frame];
- [self.view addSubview:imageView];
- self.view.backgroundColor=[UIColor blueColor];
- UIGraphicsBeginImageContext(imageView.frame.size);
- [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];
- CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
- CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 15.0); //线宽
- CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
- CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0); //颜色
- CGContextBeginPath(UIGraphicsGetCurrentContext());
- CGContextMoveToPoint(UIGraphicsGetCurrentContext(), 100, 100); //起点坐标
- CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), 200, 100); //终点坐标
- CGContextStrokePath(UIGraphicsGetCurrentContext());
- imageView.image=UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
2. 利用UIView, 我看到过有同学直接设置UIView宽或高为1来做线条:
- UIView *line_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320.f, 1.f)];
- [line_view setBackgroundColor:[UIColor redColor]];
- [self.view addSubview:line_view];
这样就是一条红色的横线lol
3. 利用UIImageView:
- UIImage *separatorImage = [UIImage imageWithRenderColor:[UIColor redColor] renderSize:CGSizeMake(320.f, 1)];
- UIImageView *topSeparatorView = [[UIImageView alloc] initWithImage:separatorImage];
- topSeparatorView.center = CGPointMake(320.f*0.5, 0.5);
- [self addSubview:topSeparatorView];
上述就是总结的三种横线画法, 当然还有其他很多方式, 有想法的可以留言.