簡體   English   中英

如何在iPhone SDK中隨機更改圖像視圖的背景色?

[英]how to change background color of image view randomly in iphone sdk?

我想隨機更改圖像視圖的背景色,但我不想設置圖像

[imageView setImage:[UIImage imageNamed:@"img1.png"]]; 通過此代碼,我想更改背景色

NSArray *colorArray = [NSArray arrayWithObjects:@"[UIColor greenColor]",@"[UIColor whiteColor]",@"[UIColor redColor]",nil];

// add all of the images to the scroll view
for (int i = 1; i < 5; i++) 
{
    imageView = [[UIImageView alloc] init];
    [imageView setBackgroundColor:[colorArray objectAtIndex:i-1]];
    [self.scrollView addSubview:imageView];

}

可以嗎? 我試過,但出現[NSCFString CGColor]錯誤。 在我的應用程序中,我想創建像這樣的應用程序 任何人都可以引導我。

您不應將字符串存儲在數組中,而應存儲實際的顏色對象。

NSArray *colorArray = [NSArray arrayWithObjects:[UIColor greenColor], [UIColor whiteColor], [UIColor redColor], nil];

另外,如果您不使用ARC,則imageView會泄漏。

如果您需要固定的4種顏色中的隨機顏色,則應按照Ecarrion的答案所述存儲顏色。 然后,您可以從中選擇一種隨機顏色。 如果您確實想要較大的顏色,可以使用

CGFloat green=(arc4random()%100) *.01;
CGFloat blue=(arc4random()%100) * .01;
CGFloat red=(arc4random()%100) *.01;
UIColor *imageBgColor=[UIColor colorWithRed:red green:green blue:blue alpha:1];
[imageView setBackgroundColor:imageBgColor];

另外,您的imageView正在泄漏。

//fix after adding as sub view to scroll view
[imageView release];
float red = arc4random() % 255 / 255.0;
float green = arc4random() % 255 / 255.0;
float blue = arc4random() % 255 / 255.0;
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
[Yourimageview setBackgroundColor:color];

生成隨機顏色R,G,B並在背景中設置Imagview。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM