Sometimes we need to self-draw uiview to achieve our own needs, such as drawing a continuous curve according to the coordinate point (stock chart), you need to draw the UIView.
Principle: Inherit the UIView Class (CustomView), and realize the drawrect of CustomView.
First look at the fruit chart:
The code is as follows:
. h
#import <UIKit/UIKit.h>
@interface CustomView: UIView
@end
. m
#import "CustomView.h"
@implementation CustomView
-(ID) initWithFrame: (cgrect) frame{
// rewrite initwithframe , don't forget the following sentence
self = [superinitwithframe: frame];
if (self) {
self. BackgroundColor = [uicolorwhitecolor];
}
return self;
}
// override DrawRect method (no call required), draw the desired image
-(void) DrawRect: (cgrect) rect{
// Get image context, note that the API can only be used in DrawRect
cgcontextref context =uigraphicsgetcurrentcontext(); //context: an area of memory painting that represents it as the current View Canvas on the line.
< Span style= "COLOR: #000000" > nsdictionary *attribute = [ Nsdictionary dictionarywithobjectsandkeys :[ uifont Systemfontofsize : 15.0f nsfontattributename Uicolor redcolor ), nsforegroundcolorattributename nil ];
< Span style= "COLOR: #000000" > [ @ " stock chart " Drawinrect: cgrectmake ( 100 200 80 20 ) withattributes:attribute]; // painting title
// start path
Cgcontextbeginpath(context);
// start point Set point
cgcontextmovetopoint(context,ten, +);
// Next coordinate point
cgcontextaddlinetopoint(context,n, +);
// One more next
cgcontextaddlinetopoint(context, ;
// One more next
cgcontextaddlinetopoint(context, a.);
// Connect coordinate points
Cgcontextstrokepath(context);
}
@end
then, in the view controller that needs to use the view,
Viewdidload add West; The following line of code is possible!
Self . View = [[customviewalloc] initwithframe: [uiscreen Mainscreen]. bounds ];
Customizing UIView for self-painting