簡單劃線,畫矩形,橢圓,填充圖等
1.首先自定義CustomView繼承自UIView
打開CustomView.h可以發現裏面有個- (void)drawRect:(CGRect)rect方法,但是被系統註釋掉了
有提示
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
就是說如果你要自定義畫圖的時候就重寫這個方法,但是一個空的方法會在執行期動畫期間造成不好的影響。重寫一般不爲空。
解鎖此方法,我們在此方法中進行繪圖。
-(void)drawRect:(CGRect)rect
{
//首先獲得上下文(畫布)
CGContextRef context=UIGraphicsGetCurrentContext();
//你將要劃線的顏色設置(畫筆顏色)
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 2);//劃線寬度
//畫直線
//移動到點(50,50)
//添加一條線到(100,100)
//畫線
CGContextMoveToPoint(context, 50, 50);
CGContextAddLineToPoint(context, 100, 100);
CGContextStrokePath(context);
//畫另一條線,中間可以改變顏色
CGContextMoveToPoint(context, 100, 100);
CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
CGContextAddLineToPoint(context, 200, 100);
CGContextStrokePath(context);
//畫圓
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextStrokeEllipseInRect(context, CGRectMake(20, 120, 50, 50));
//畫橢圓
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextStrokeEllipseInRect(context, CGRectMake(100, 120, 80, 30));
//畫矩形
CGContextSetStrokeColorWithColor(context, [UIColor cyanColor].CGColor);
CGContextStrokeRect(context, CGRectMake(200, 120, 50,40));
//畫填充圖
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGRect fillRect=CGRectMake(120, 160, 50, 30);
CGContextFillEllipseInRect(context, fillRect);
}
當然還有其它很多圖形都可以畫,就自己嘗試吧