IOS uses CGContextRef to dynamically draw a line chart

Source: Internet
Author: User

IOS uses CGContextRef to dynamically draw a line chart

-(Void) drawRect :( CGRect) rect {CGContextRef context = UIGraphicsGetCurrentContext (); CGContextClearRect (context, rect); CGContextSetLineWidth (context, _ lineWidth ); // set the paint brush width CGContextSetFillColorWithColor (context, [[self backgroundColor] CGColor]); // set the background fill color CGContextFillRect (context, rect); // fill the background CGContextSetStrokeColorWithColor (context, _ lineColor. CGColor); // set the paint brush color // arr to the dynamic data array obtained in real time for (int I = 0; I <_ arr. count; I ++) {if (I <_ arr. count-1) {CGPoint pp [2]; [_ arr [I] getBytes: & pp [0] length: sizeof (CGPoint)]; [_ arr [I + 1] getBytes: & pp [1] length: sizeof (CGPoint)]; CGContextMoveToPoint (context, pp [0]. x, pp [0]. y); CGContextAddLineToPoint (context, pp [1]. x, pp [1]. y); CGContextStrokePath (context) ;}}- (void) addDataToArr :( CGFloat) data {if (! _ Arr) _ arr = [[NSMutableArray alloc] init]; CGPoint point; // MAX_X_COUNT indicates the maximum number displayed on the X axis. If it is exceeded, the X axis moves to the left, move one unit each time if (_ arr. count> = MAX_X_COUNT) {// move the X axis CGRect frame = self. frame; frame. origin. x-= (self. frame. size. width/MAX_X_COUNT); frame. size. width + = (self. frame. size. width/MAX_X_COUNT); self. frame = frame;} point. x = _ arr. count * (self. frame. size. width/MAX_X_COUNT); // if the current value is greater than the maximum value represented by the Y axis, the maximum value of the Y axis is expanded to 2 times that of the current value if (data> _ maxYPower) {// change the maximum value of y to currentPower _ maxYPower = data * 2;} point. y = data; // Save the data obtained in real time to _ arr [_ arr addObject: [NSData dataWithBytes: & point length: sizeof (CGPoint)];}
You only need to dynamically call addDataToArr: And then call [self. view setNeedDisplay ].

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.