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

随声附和 提交于 2019-12-02 19:45:10
willc2

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

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

Put this code in the drawRect: method of your SquareView.m file to draw a large, crooked, 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 don't have to call this method for the drawing to happen. Your view controller will tell the view to draw itself at least once when the program launches and the NIB files are activated.

You are not supposed to put CG code in initWithCoder. That message should only be used for INITIALIZATION purpose.

Put your drawing code in:

- (void)drawRect:(CGRect)rect

If you are subclassing a UIView...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!