【问题标题】:How to keep an image from going out side of a set area如何防止图像超出设定区域
【发布时间】:2014-04-02 01:46:54
【问题描述】:

我正在努力做到这一点,当您触摸图像时,它会移动到一个随机位置,但我现在意识到我需要它留在一个固定的空间中,这样我就可以添加诸如计分器之类的东西。我遇到的问题是我不知道如何执行此操作,因此感谢您提供任何帮助。

我的代码:

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

}

谢谢。

【问题讨论】:

    标签: ios iphone xcode xcode4.6


    【解决方案1】:

    您可以使用具有所需框架的 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];
    

    【讨论】:

      【解决方案2】:

      如果你有一个 UIImageView 属性叫做movingImageView 作为子视图,试试这个:

      -(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 的边界大于或等于容器的边界时,事情就会中断。

      这与您已经拥有的代码几乎相同,如果“图像”实际上包含在 UIButton 中,您可以将方法声明更改为:

      -(IBAction)hideImage:(id)sender {
         UIView *containerView = self.view;
         UIView *movingView = (UIView *)sender
         ... The rest is same as above ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 1970-01-01
        • 2011-09-18
        • 2019-04-16
        • 1970-01-01
        • 2014-05-29
        • 2018-06-09
        相关资源
        最近更新 更多