2014-03-07 4 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); 

}

나는 여전히 어떤 도움이 감사합니다 아이폰 OS에 아주 새로운 해요, 감사합니다.

답변

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을 시도 unneccesary된다. :피 –

0

보십시오 : 직접이 다음

int x = 240; 

int y = 160; 

image.center = CGPointMake(x, y); 

: 또한

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 xr = arc4random() % (int) self.view.frame.size.width; 

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

image.center = CGPointMake(xr, yr); 

첫 번째 과제는

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