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]:. 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.
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. 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.
//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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.