標籤:ios 畫線 分割線 橫線 cgcontext
很多控制項中希望加一條線, 常見橫的豎的, 比如在一個頁面的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];
這其實就是加入一張圖片.
上述就是總結的三種橫線畫法, 當然還有其他很多方式, 有想法的可以留言.
IOS畫線的問題