我试图这样做,当你触摸图像时它移动到一个随机点,但我现在意识到我需要它留在一个固定的空间,所以我可以添加像分数计数器的东西。我遇到的问题是我不知道如何做到这一点,所以任何帮助都会受到赞赏。
我的代码:
-(IBAction)hideImage {
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);
}
谢谢。
答案 0 :(得分:0)
您可以使用具有所需框架的UIView。然后将UIImageView添加到UIView并设置:
[thisView setClipsToBounds: YES];
所以:
CGRect myBounds = CGRectMake(0, 0, 320, 300);
UIView* thisView = [[UIView alloc] initWithFrame: myBounds];
[self.view addSubview: thisView];
UIImageView* image = [[UIImageView alloc] initWithFrame:...];
//Other image code
[thisView addSubview: image];
[thisView setClipsToBounds: YES];
答案 1 :(得分:0)
如果你有一个名为movingImageView的UIImageView属性作为子视图,请尝试:
-(IBAction)hideImage {
UIView *containerView = self.view;
UIView *movingView = self.movingImageView;
CGFloat xRange = CGRectGetWidth(containerView.bounds) - CGRectGetWidth(movingImageView.bounds);
CGFloat yRange = CGRectGetHeight(containerView.bounds) - CGRectGetHeight(movingImageView.bounds);
CGFloat minX = CGRectGetMidX(movingImageView.bounds);
CGFloat minY = CGRectGetMidY(movingImageView.bounds);
NSInteger randomX = (arc4random() % (NSInteger)floorf(xRange)) + minX;
NSInteger randomY = (arc4random() % (NSInteger)floorf(yRange)) + minY;
self.movingImageView.center = CGPointMake(randomX, randomY);
}
当imageView的边界大于或等于容器的边界时,事物就会中断。
这与您已经拥有的代码几乎相同,如果'image'实际包含在UIButton中,您可以将方法声明更改为:
-(IBAction)hideImage:(id)sender {
UIView *containerView = self.view;
UIView *movingView = (UIView *)sender
... The rest is same as above ...