ViewController.m
#import "ViewController.h"
#import "DrawerView.h"
#define KScreenWidth [UIScreen mainScreen].bounds.size.width
#define KScreenHeight [UIScreen mainScreen].bounds.size.height
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//有View >loadView >Xib >創(chuàng)建空白View >ViewDidLoad
//DrawRect :方法 是繪制UIView的方法
DrawerView *drawer = [[DrawerView alloc]initWithFrame:CGRectMake(0, 20, KScreenWidth, 400)];
drawer.backgroundColor = [UIColor whiteColor];
self.view.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:drawer];
}
@end
DrawerView.m
#import "DrawerView.h"
@implementation DrawerView
- (void)drawRect:(CGRect)rect{
NSLog(@"drawRact");
[self drawLine];
}
- (void)drawLine{
//1.獲取當前視圖相關的上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//2.路徑
//創(chuàng)建路徑對象
CGMutablePathRef path= CGPathCreateMutable();
//起點
CGPathMoveToPoint(path, NULL, 0, 5);
//添加路徑點
CGPathAddLineToPoint(path, NULL, 300, 5);
CGPathAddLineToPoint(path, NULL, 300, 200);
//設置路徑閉環(huán)
CGPathCloseSubpath(path);
//3.上下文屬性
//填充顏色
CGContextSetRGBFillColor(context, 212/255.0, 24/255.0, 148/255.0, 1);
//線條寬度
//如果是OC -->[context setLineWidth:5];
CGContextSetLineWidth(context, 2);
//線條顏色(默認黑色) (0,0,0)是黑色 (1,1,1)是白色
CGContextSetRGBStrokeColor(context, 68/255.0, 178/255.0, 249/255.0, 1);
//線條首尾樣式
/**
* kCGLineCapButt,
kCGLineCapRound, 圓弧
kCGLineCapSquare 方形
*/
CGContextSetLineCap(context, kCGLineCapButt);
//線條鏈接樣式
/**
* kCGLineJoinMiter, 默認
kCGLineJoinRound, 圓弧
kCGLineJoinBevel 斜線
*/
CGContextSetLineJoin(context, kCGLineJoinBevel);
//虛線定制
/**
* context : 上下文對象
phase : 虛線起點與路徑起點的距離
lengths : C數組 從數組中循環(huán)獲取虛線長度和間隔
count : 數組長度
*/
CGFloat lengths[] = {15,15,15};
CGContextSetLineDash(context, 0, lengths, 3);
//4.路徑結合上下文
CGContextAddPath(context, path);
//5.繪制路徑
/**
* kCGPathFill, 填充
kCGPathEOFill,
kCGPathStroke, 畫線
kCGPathFillStroke, 畫線+填充
kCGPathEOFillStroke
*/
CGContextDrawPath(context, kCGPathStroke);
屏幕快照 2016-03-14 下午5.08.42.png
//6.釋放路徑
CGPathRelease(path);
}
@end
屏幕快照 2016-03-14 下午5.05.12.png