如何在iPhone SDK中随机更改图像视图的背景颜色?
问题描述:
我想改变图像视图的背景颜色随机我不想通过如何在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] :.在我的应用程序中,我想创建like this application。任何人都可以指导我。
答
你不应该在你的数组中存储字符串,存储实际的颜色对象。
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。
感谢兄弟,但你有什么想法创建[那种应用](http://itunes.apple.com/us/app/flashlight./id285281827?mt=8)?如果是的话,那对我来说会很有帮助。 – 2011-12-24 06:00:43
这是一个相当开放的问题,如果你有特别的疑问,你可以在这里问,如果不是真的很难知道你在想什么。 – Ecarrion 2011-12-24 06:03:44