Draw:
Create Drawview, Inherit UIView (written in C) (OC with [] call, C direct call, parameter put back)
In Viewcontroller, the code will execute this method, the view's class is set to Drawview directly in the STORYBOARDL, the initWithFrame method is not executed, and the Initwithcode is executed.
-(Instancetype) initWithFrame: (CGRect) frame
{
self = [super Initwithframe:frame];
if (self) {
Self.backgroundcolor = [Uicolor Clearcolor];
}
return self;
}
This initialization method is called when a control is created through SB or xib
-(Instancetype) Initwithcoder: (Nscoder *) coder
{
self = [super Initwithcoder:coder];
if (self) {
Self.points = [Nsmutablearray array];
}
return self;
}
The first time this method is displayed, it is automatically called once, and then each time the Setneeddisplay (setting needs to be displayed) method is executed.
Set a brush to draw a line
-(void) DrawRect: (CGRect) rect{
Get context
Cgcontextref context = Uigraphicsgetcurrentcontext ();
Set the color of the line
Cgcontextsetstrokecolorwithcolor (context, [Uicolor Greencolor]. Cgcolor);
Move a brush to a location
Cgcontextmovetopoint (context, 20, 200);
Add a line to a point
Cgcontextaddlinetopoint (context, 120, 300);
Cgcontextaddlinetopoint (context, 220, 100);
Draw
Cgcontextdrawpath (context, kcgpathstroke);
}
Set a brush to draw a line
-(void) DrawRect: (CGRect) rect{
Get context
Cgcontextref context = Uigraphicsgetcurrentcontext ();
Set the color of the line
Cgcontextsetstrokecolorwithcolor (context, [Uicolor Greencolor]. Cgcolor);
for (int i; i<self.points.count; i++) {//traverse each point
Cgpoint p = [self.points[i] cgpointvalue];
if (i ==0) {
Cgcontextmovetopoint (context, p.x, p.y); Move the brush to a point
}else{
Cgcontextaddlinetopoint (context, p.x, p.y); Add a line to a point
}
}
Draw
Cgcontextdrawpath (context, kcgpathstroke);
}
-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{
Uitouch *t = [touches anyobject];
Cgpoint p = [t locationinview:self];
[Self.points Addobject:[nsvalue valuewithcgpoint:p];
}
-(void) touchesmoved: (Nsset *) touches withevent: (uievent *) event{
Uitouch *t = [touches anyobject];
Cgpoint p = [t locationinview:self];
[Self.points Addobject:[nsvalue valuewithcgpoint:p];
[Self setneedsdisplay];
}
Lan Yi Education Drawing