2014-03-07 108 views
0

我試圖做到這一點,當你觸摸UIImage它會移動到一個隨機點,但它會在兩次或多次移動後繼續離開屏幕。我試圖重置它,因爲它會移動到一個隨機點,但它仍然會關閉屏幕。 那麼有沒有一種方法可以判斷它是否脫離屏幕,或者我只是錯過了一些東西?如何停止屏幕上的圖像?

-(IBAction)moveimage { 
    int x = 240; 
    int y = 160; 

    image.center = CGPointMake(x, y); 

    int xr = arc4random() % (int) self.view.frame.size.width; 
    int yr = arc4random() % (int) self.view.frame.size.height; 

    image.center = CGPointMake(xr, yr); 

}

我還是很新的到iOS所以任何幫助表示讚賞,謝謝。

回答

0

小心你的xr和yr類型。 CGPoint是2 CGFloat的結構(即在64位體系結構上是雙重的)。

0
int xr = arc4random() % (int) self.view.frame.size.width; 

int yr = arc4random() % (int) self.view.frame.size.height; 

xr = MAX(image.frame.size.width , xr); // left edge detect 
xr = MIN(image.superview.frame.size.width - image.frame.size.width , xr); //right edge detect 

yr = MAX(image.frame.size.height , yr); // top edge detect 
yr = MIN(image.superview.frame.size.height - image.frame.size.height , yr); //bottom edge detect 

image.center = CGPointMake(xr, yr); 
+0

右+1你。 :P –

0

嘗試用以下替換代碼:

CGFloat xRange = self.view.bounds.size.width - image.bounds.size.width; 
CGFloat yRange = self.view.bounds.size.height - image.bounds.size.height; 

CGFloat minX = self.view.center.x - (xRange/2); 
CGFloat minY = self.view.center.y - (yRange/2); 

int randomX = (arc4random() % (int)floorf(xRange)) + minX; 
int randomY = (arc4random() % (int)floorf(yRange)) + minY; 
image.center = CGPointMake(randomX, randomY); 

而且,只是在你原來的代碼註釋,當您運行以下命令:

int x = 240; 

int y = 160; 

image.center = CGPointMake(x, y); 

直接跟着這樣的:

int xr = arc4random() % (int) self.view.frame.size.width; 

int yr = arc4random() % (int) self.view.frame.size.height; 

image.center = CGPointMake(xr, yr); 

你的第一個任務變成unneccesary

0

試試這個

-(IBAction)moveimage { 

    int x = 240; 
    int y = 160; 

    image.center = CGPointMake(x, y); 

    int newx =[self getRandomNumberBetween:self.view.bounds.size.width-imageWidth 
           maxNumber:self.view.bounds.size.height-imageHeight]; 
    int newy =[self getRandomNumberBetween:self.view.bounds.size.width-imageWidth 
           maxNumber:self.view.bounds.size.height-imageHeight]; 

    CGRect newFrame=[image frame]; 
    newFrame.origin.x = newx; 
    newFrame.origin.y = newy; 

    [image setFrame:newFrame]; 
} 

- (NSInteger)getRandomNumberBetween:(NSInteger)min 
          maxNumber:(NSInteger)max{ 
    return min + arc4random() % (max - min + 1); 
}