2013-10-07 20 views
0

好的,所以我總共有5個自定義圖像。 繼承人的價值觀,我需要設置每個圖像:如何爲圖像分配值

Image1 = 1 
Image2 = 2 
Image3 = 3 
Image4 = 4 
Image5 = 5 

,因爲我想擁有的Xcode隨機把他們放在視圖,直到達到50的數值因此Im假設我需要,我需要分配給這些值某種循環加起來的值直到達到50?

如何爲這些圖像指定值,因爲它會在嘗試將一個int值分配給UIImage時引發警告。另外,在旁邊注意我會用什麼方法將圖像隨機放置在視圖上而不重疊?

感謝您的幫助!

+0

不知道我是否正確地得到了您的問題。如果你有對圖像名稱的控制,你可以用後綴或前綴1,2,3來命名它,直到50.然後使用數組並創建像這樣的隨機數http://stackoverflow.com/questions/1617630/non-repeating- random-numbers – thndrkiss

+0

當它得到多個答案並解決用戶問題時,看到一個問題被擱置爲「不清楚你問什麼」的問題總是很有趣。 – HalR

回答

3

你的應用程序將被放置UIImageView S,不UIImage小號到一個視圖。像所有UIView小類,UIImageView有一個NSIntegertag財產,但如果我正確地理解問題,我不認爲你也需要這個。

// add count randomly selected images to random positions on self.view 
// (assumes self is a kind of UIViewController) 
- (void)placeRandomImages:(NSInteger)count { 

    for (NSInteger i=0; i<count; ++i) { 
     UIImage *image = [self randomImage]; 
     UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 
     imageView.frame = [self randomFrameForImage:image]; 
     [self.view addSubview:imageView]; 

     // add a tag here, if you want, but I'm not sure what for 
     // imageView.tag = i; 
    } 
} 

// answer a random image from the app's bundle 
// assumes the images are named image-x where x = 0..4 
- (UIImage *)randomImage { 

    NSInteger imageNumber = arc4random() % 5; 
    NSString *imageName = [NSString stringWithFormat:@"image-%d", imageNumber]; 
    return [UIImage imageNamed:imageName]; 
} 

// answer a random position for the passed image, keeping it inside the view bounds 
- (CGRect)randomFrameForImage:(UIImage *)image { 

    CGFloat imageWidth = image.width; 
    CGFloat imageHeight = image.height; 

    CGFloat maxX = CGRectGetMaxX(self.view.bounds) - imageWidth; 
    CGFloat maxY = CGRectGetMaxY(self.view.bounds) - imageHeight; 

    // random location, but always inside my view bounds 
    CGFloat x = arc4random() % (NSInteger)maxX; 
    CGFloat y = arc4random() % (NSInteger)maxY; 

    return CGRectMake(x,y,imageWidth,imageHeight); 
} 
+0

+1多個實現。 –

+0

使用'arc4random_uniform()'來避免模偏差。 – danielbeard

+0

嘿danh,正在尋找一個消息功能來問你這個問題,但我不認爲有一個。在你的代碼行UIImageView * imageView = [UIImageView imageViewWithImage:image]; image.frame = [self randomFrameForImage:image]; imageViewWithImage部分Xcode說「沒有已知的選擇器類方法」。並且在image.frame下方顯示「在'UIImage'類型的對象上找不到」屬性框架「」有任何信息可以清除此問題,我們將不勝感激 – iann

2

如果想分配一個任意的整數值,我會在UIImageView上使用標籤屬性。

NSInteger currentTag = 50; 
while (currentTag > 0) { 
     UIImageView *imageView = [UIImageView alloc initWithImage:image]; 
     imageView.tag = currentTag; 
     [self.view addSubView:imageView]; 
     currentTag--; 
    } 
0

把圖像轉換成一個NSArray然後從NSHipster

如何從一個NSArray

使用arc4random_uniform選擇一個隨機元(3)在一個範圍內產生一個隨機數非空數組。

if ([array count] > 0) { 
    id obj = array[arc4random_uniform([array count])]; 
}