当我触摸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 :(得分:0)
小心你的xr和yr类型。 CGPoint是2 CGFloat的结构(即在64位架构上加倍)。
答案 1 :(得分: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);
答案 2 :(得分: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);
您的第一个作业变得不必要
答案 3 :(得分: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);
}