[英]how to change background color of image view randomly in iphone sdk?
I want to change background color of image view randomly i don't want to set images by 我想随机更改图像视图的背景色,但我不想设置图像
[imageView setImage:[UIImage imageNamed:@"img1.png"]];
by this code i want to change background color 通过此代码,我想更改背景色
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];
}
Can it is possible? 可以吗? i tried but i get error of [NSCFString CGColor]:.
我试过,但出现[NSCFString CGColor]错误。 in my application i want to create like this application .
在我的应用程序中,我想创建像这样的应用程序 。 can any body guide me.
任何人都可以引导我。
You shouldn't be storing string in your array, store the actual colors objects. 您不应将字符串存储在数组中,而应存储实际的颜色对象。
NSArray *colorArray = [NSArray arrayWithObjects:[UIColor greenColor], [UIColor whiteColor], [UIColor redColor], nil];
Also, if you're no using ARC, your imageView is leaking. 另外,如果您不使用ARC,则imageView会泄漏。
If you need random colors out of a fixed set of 4 colors, you should store the colors as mentioned in the answer by Ecarrion. 如果您需要固定的4种颜色中的随机颜色,则应按照Ecarrion的答案所述存储颜色。 Then you could select a random color out of that.
然后,您可以从中选择一种随机颜色。 If you truly want a random color in a larger set, you could use
如果您确实想要较大的颜色,可以使用
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];
Also your imageView is leaking. 另外,您的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];
Generate a random color R,G,B and set Imagview in Background. 生成随机颜色R,G,B并在背景中设置Imagview。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.