介紹兩種畫直線的方法:
(1)通過QuartzCore
(2)通過UIBezierPath
先建立一個自定義view:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiNzcjNwgDNwITOxUDM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
然後在導入QuartzCore架構:
然後在m檔案打出下面代碼,三種函數都是同樣的效果:
#import "ZCView.h"
#import <QuartzCore/QuartzCore.h>
@implementation ZCView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
*/
- (void)drawRect:(CGRect)rect {
[self drawLine3];
}
- (void)drawLine1
{
//擷取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//設定路徑
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, , );
CGPathAddLineToPoint(path, NULL, , );
//添加路徑
CGContextAddPath(context, path);
//畫上去
CGContextStrokePath(context);
}
- (void)drawLine2
{
//擷取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//設定路徑
CGContextMoveToPoint(context, , );
CGContextAddLineToPoint(context, , );
//畫上去
CGContextStrokePath(context);
}
- (void)drawLine3
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(, )];
[path addLineToPoint:CGPointMake(, )];
[path stroke];
}
@end
在drawRect函數裡面調用不同的函數就行了,效果如下: