Pergunta

My code was working when I was using UIViews and changing their background color. Now I try it with ellipses and they don't show up? Here is the code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
        overlayView = [[[UIView alloc] initWithFrame:self.view.bounds] autorelease];
        overlayView.backgroundColor = [UIColor colorWithWhite:255.0f alpha:1.0f];
    [self.view addSubview:overlayView];
    reda = 0;
    bluea = 0;
    greena = 255;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    touchPoint = [touch locationInView:self.view];
    previousPoint = touchPoint;

}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    touchPoint = [touch locationInView:self.view];
    if (abs((previousPoint.x-touchPoint.x)) > 20) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Too Fast!" delegate:self cancelButtonTitle:@"Okay." otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(contextRef, reda/255.f, greena/255.f, bluea/255.f, 1.0f);
    CGContextFillEllipseInRect(contextRef, CGRectMake(touchPoint.x, touchPoint.y, 20, 20));
    [overlayView addSubview:contextRef];

    if ((greena != 0) && (bluea == 0)) {
        greena += -5;
        reda += +5;
    }
    if ((reda != 0) && (greena == 0)) {
        bluea += +5;
        reda += -5;
    }
    if ((bluea != 0) && (reda == 0)) {
        bluea += -5;
        greena += +5;
    }
}
Foi útil?

Solução

You are calling UIGraphicsGetCurrentContext in touchesMoved:withEvent:. The system doesn't create a graphics context for you in touchesMoved:withEvent:. The system only creates a graphics context for you in -[UIView drawRect:].

You need to read about the view drawing cycle and the runtime interaction model for views in Apple's documentation.

You can either move your drawing code to drawRect:, or you can create your own graphics context (e.g. using UIGraphicsBeginImageContextWithOptions or CGBitmapContextCreate), draw to it, and then create an image from the context and assign the image to view.layer.contents.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top