kyle
kyle

Reputation: 31

Drawing circles in Core Graphics - why isn't this working?

I'm trying to create a simple drawing app that creates circles wherever you put your finger, this is what I have:

@synthesize touchPos;
@synthesize coords;


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    touchPos = [touch locationInView:self.view];
    coords.text = [NSString stringWithFormat:@"%3.0f, %3.0f", touchPos.x, touchPos.y];
    [self setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesBegan:touches withEvent:event];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(contextRef, 2.0);
    CGContextSetRGBFillColor(contextRef, 0, 0, 1.0, 1.0);
    CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
    CGRect circlePoint = (CGRectMake(touchPos.x, touchPos.y, 10.0, 10.0));

    CGContextFillEllipseInRect(contextRef, circlePoint);
}

I don't get any errors or warnings, it just doesn't draw anything. Also, the text box shows the coordinates wherever I'm touching, so I know that's not the problem.

Upvotes: 3

Views: 3193

Answers (3)

Alex Nichol
Alex Nichol

Reputation: 7510

The issue is that -drawRect: isn't being called because, that's right, your writing this code in a UIViewController. You need to make a subclass of UIView and move all of this drawing and event handling to it. The only thing that you should need to change is self.view, since in a subclass of UIView you will just need to say self. Once you have a custom UIView subclass, you can use interface builder to set the class of your UIViewController to your custom class.

Upvotes: 0

progrmr
progrmr

Reputation: 77191

Did you call addSubview to add this to the main view? Did you call setNeedsDisplay for this view?

See also this SO question.

Make sure the frame is correct and within the bounds of the parent view.

Upvotes: 1

hotpaw2
hotpaw2

Reputation: 70693

This code needs to be in a UIView subclass that is part of the current view hierarchy.

Upvotes: 3

Related Questions