2012-10-06 88 views
1

當我使用UIViews並改變它們的背景顏色時,我的代碼正在工作。現在我用橢圓嘗試它,他們不顯示?下面是代碼:iOS touch中的繪圖圈移動了

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

回答

2

要調用的touchesMoved:withEvent:UIGraphicsGetCurrentContext。系統不會在touchesMoved:withEvent:中爲您創建圖形上下文。系統僅在-[UIView drawRect:]中爲您創建圖形上下文。

您需要閱讀Apple文檔中的view drawing cycleruntime interaction model for views

您可以將您的繪圖代碼drawRect:,或者你可以創建自己的圖形上下文(例如使用UIGraphicsBeginImageContextWithOptionsCGBitmapContextCreate),畫它,然後創建從上下文的圖像,並分配給view.layer.contents

+0

完美!對CGBitmapContextCreate非常好,並將其製作爲UIImage,並將其放入UIImageView並使用addtosubview添加該視圖! –