开发者

Problem in drawing square in sample app

Hi i am making a sample app in which i wanto create a square for which i used the following code

- (void)viewDidLoad {
    [super viewDidLoad];
    [self drawRect:CGRectMake(0, 0, 300, 200)];
    [[self view] setNeedsDisplay];
}
- (void) drawRect:(CGRect)rect
{
    NS开发者_开发技巧Log(@"drawRect");

    CGFloat centerx = rect.size.width/2;
    CGFloat centery = rect.size.height/2;
    CGFloat half = 100/2;
    CGRect theRect = CGRectMake(-half, -half, 100, 100);

    // Grab the drawing context
    CGContextRef context = UIGraphicsGetCurrentContext();

    // like Processing pushMatrix
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, centerx, centery);

    // Uncomment to see the rotated square
    //CGContextRotateCTM(context, rotation);

    // Set red stroke
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);

    {
        CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1.0);
    }
    // Draw a rect with a red stroke
    CGContextFillRect(context, theRect);
    CGContextStrokeRect(context, theRect);

    // like Processing popMatrix
    CGContextRestoreGState(context);
    [[self view] setNeedsDisplay];

}

But nothing is drawn on screen , dont know wheres the issue is .When i debug it the CGContextRef context was always 0x0 , i dont know why its 0x0 always am i missing something in my code.


It looks like you're trying to draw in a subclass of UIViewController. You need to subclass UIView to override the drawRect: method, which is then called automatically with a valid graphics context in place. You almost never call this method yourself.


To quote the Apple docs:

"To draw to the screen in an iOS application, you set up a UIView object and implement its drawRect: method to perform drawing. The view’s drawRect: method is called when the view is visible onscreen and its contents need updating. Before calling your custom drawRect: method, the view object automatically configures its drawing environment so that your code can start drawing immediately. As part of this configuration, the UIView object creates a graphics context (a CGContextRef opaque type) for the current drawing environment. You obtain this graphics context in your drawRect: method by calling the UIKit function UIGraphicsGetCurrentContext."

So essentailly, your code is on track, you just need to get it in the right place. It needs to be in the View object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜