簡單繪圖(一)

簡單劃線,畫矩形,橢圓,填充圖等

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);//劃線寬度

    

    //畫直線

    //移動到點(5050

    //添加一條線到(100100

    //畫線

    CGContextMoveToPoint(context, 5050);

    CGContextAddLineToPoint(context, 100100);

    CGContextStrokePath(context);


    //畫另一條線,中間可以改變顏色

    CGContextMoveToPoint(context, 100100);

    CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);

    CGContextAddLineToPoint(context, 200100);

    CGContextStrokePath(context);


    //畫圓

    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);

    CGContextStrokeEllipseInRect(context, CGRectMake(201205050));

    

    //畫橢圓

    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);

    CGContextStrokeEllipseInRect(context, CGRectMake(1001208030));

    

    //畫矩形

    CGContextSetStrokeColorWithColor(context, [UIColor cyanColor].CGColor);

    CGContextStrokeRect(context, CGRectMake(20012050,40));

    

    //畫填充圖

    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);

    CGRect fillRect=CGRectMake(1201605030);

    CGContextFillEllipseInRect(context, fillRect);

}


當然還有其它很多圖形都可以畫,就自己嘗試吧

發佈了11 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章