开发者

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

开发者 https://www.devze.com 2023-03-22 16:20 出处:网络
I\'m trying to create a simple drawing app that creates circles wherever you 开发者_开发问答put your finger, this is what I have:

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.


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


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.


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.

0

精彩评论

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