1

当我使用 UIViews 并更改它们的背景颜色时,我的代码正在工作。现在我用椭圆尝试它,但它们没有出现?这是代码:

- (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;
    }
}
4

1 回答 1

2

你在UIGraphicsGetCurrentContext打电话touchesMoved:withEvent:。系统不会在touchesMoved:withEvent:. 系统仅在-[UIView drawRect:].

您需要阅读Apple 文档中 有关视图绘制周期和视图运行时交互模型的信息。

您可以将绘图代码移动到drawRect:,也可以创建自己的图形上下文(例如使用UIGraphicsBeginImageContextWithOptionsCGBitmapContextCreate),绘制到它,然后从上下文创建图像并将图像分配给view.layer.contents

于 2012-10-06T05:12:01.217 回答