Customizing UIView for self-painting

Source: Internet
Author: User

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

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.