cocoa touch - Objective-C costum drawing with draw: (CGContextRef *)context -


i have home work our professor told make circle, square, , triangle confirm protocol called

shape.h:

#import <foundation/foundation.h>  @protocol shape <nsobject>  @required - (void)draw:(cgcontextref) context; - (float)area;  @end 

and use uibotton call different class draw..

i call draw function view controller

xyzcontroller.m:

- (ibaction)rectbutton:(id)sender {     cgrect frame = [myview bounds];      myrect *rectview = [[myrect alloc] initwithframe:frame];      [rectview draw: uigraphicsgetcurrentcontext()];     [myview addsubview:rectview]; } 

where myview uiview dragged onto .xib

and perform draw in myrect class

myrect.h:

@interface myrect : uiview <shape> 

i changed super class nsobject uiview... not sure if did correctly..

myrect.m:

- (id)initwithframe:(cgrect)frame {     self = [super initwithframe:frame];     if (self) {         [self setneedsdisplay];     }      return self; }  - (void)draw : (cgcontextref) context {     cgrect bounds = [self bounds];      cgrect originrect = cgrectmake(25.0, 25.0, 50.0, 75.0);      cgcontextaddrect(context, originrect);     cgcontextstrokepath(context);     [[uicolor greencolor] setfill];     cgcontextfillrect(context, originrect); } 

but got error:

[...] <error>: cgcontextsetfillcolorwithcolor: invalid context 0x0 [...] <error>: cgcontextaddrect: invalid context 0x0 [...] <error>: cgcontextfillrects: invalid context 0x0 

i guess it's [rectview draw: uigraphicsgetcurrentcontext()];

any idea of how fix this?

thanks!

you first of overwrite -drawrect: method in myrect class. , use

[[uicolor greencolor] set] // or setstroke, 'cause using stroke , not fill! cgcontextstrokerect(uigraphicsgetcurrentcontext(), rect) 

you should use -drawrect: , make drawing in uiview subclass. can not context want. in named method.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -