Beginner iphone question: drawing a rectangle. What am I doing wrong?

Trying to figure out what I'm doing wrong here. I tried a few things, but I never see this elusive rectangle on the screen. Right now, all I want to do is just draw one rectangle on the screen.

I get an "invalid context" for everything except CGContextSetRGBFillColor (). Getting the context after that seems wrong to me, but I'm not at home looking at the examples I used last night.

Did I mess up something else too? I really would like to at least do it tonight ...

- (id)initWithCoder:(NSCoder *)coder { CGRect myRect; CGPoint myPoint; CGSize mySize; CGContextRef context; if((self = [super initWithCoder:coder])) { NSLog(@"1"); currentColor = [UIColor redColor]; myPoint.x = (CGFloat)100; myPoint.y = (CGFloat)100; mySize.width = (CGFloat)50; mySize.height = (CGFloat)50; NSLog(@"2"); // UIGraphicsPushContext (context); NSLog(@"3"); CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, currentColor.CGColor); CGContextAddRect(context, myRect); CGContextFillRect(context, myRect); } return self; } 

Thanks,

Sean.

+7
iphone quartz-graphics draw
source share
2 answers

Starting with a presentation-based template, create a project named Box . Add the UIView class to your project. Name it SquareView (.h and .m).

Double-click DrawerViewController.xib to open it in Interface Builder. Change the general view there of SquareView in the Identity Inspector (command-4) using the Class pop-up menu. Save and go back to Xcode .

Put this code in the drawRect: method of your SquareView.m file to draw a large, curved, empty yellow rectangle and a small, green, transparent square:

 - (void)drawRect:(CGRect)rect; { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line CGContextBeginPath(context); CGContextMoveToPoint(context, 50.0, 50.0); //start point CGContextAddLineToPoint(context, 250.0, 100.0); CGContextAddLineToPoint(context, 250.0, 350.0); CGContextAddLineToPoint(context, 50.0, 350.0); // end path CGContextClosePath(context); // close path CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it CGContextStrokePath(context); // do actual stroking CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner } 

You do not need to call this method to draw. The controller of your view will tell you that the view will be displayed at least once when you start the program and activate the NIB files.

+40
source share

You should not enter CG code in initWithCoder . This message should only be used for INITIALIZATION purposes.

Put the drawing code in:

 - (void)drawRect:(CGRect)rect 

If you subclass UIView ...

+9
source share

All Articles