2014-04-02 81 views
0

我試圖讓它如此,當你觸摸圖像時,它會移動到一個隨機點,但我現在意識到我需要它留在一個設定的空間所以我可以添加比分計數器等東西。我遇到的問題是,我不知道如何做到這一點,所以任何幫助表示讚賞。如何從設置區域的外側保留圖像

我的代碼:

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

您可以使用具有所需幀的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]; 
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的邊界大於或等於容器邊界的東西將會破壞。

這是相當多的,你已經有相同的代碼,如果「形象」實際上是包含在一個UIButton,你可以改變方法聲明爲:

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