How to assign values to images [closed] - iphone

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Alright, so I have 5 custom images total.
Heres the values I need to set each image to:
Image1 = 1
Image2 = 2
Image3 = 3
Image4 = 4
Image5 = 5
I need values assigned to these because I want to have xcode randomly place them on the view until it reaches a value of 50. So im assuming I need some kind of loop that adds up the values until 50 is reached?
How do I assign values to these images since it brings up a warning when trying to assign an int value to a UIImage. Also, on a side note what method would I use to randomly place the images on the view without overlapping?
Thanks for any and all help!

Your app will be placing UIImageViews, not UIImages onto a view. Like all UIView subclasses, UIImageView has an NSInteger tag property, but if I understand the problem correctly, I don't think you need that, either.
// 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);
}

If want to assign an arbitrary integer value, I would use the tag property on UIImageView.
NSInteger currentTag = 50;
while (currentTag > 0) {
UIImageView *imageView = [UIImageView alloc initWithImage:image];
imageView.tag = currentTag;
[self.view addSubView:imageView];
currentTag--;
}

Put the images into an NSArray then from NSHipster:
How Do I Pick a Random Element from an NSArray
Use arc4random_uniform(3) to generate a random number in the range of a non-empty array.
if ([array count] > 0) {
id obj = array[arc4random_uniform([array count])];
}

Related

Move images to random placeholders

I have a simple jigsaw puzzle i'm making. I have a method that is called when the view is loaded and when the device is shaken. This method places 4 images in 4 specific places on screen. Below is the code:
-(void) makePieceHolders {
//create 4 points where the jigsaw pieces (images) will be placed
CGPoint holder1 = CGPointMake(80, 80);
CGPoint holder2 = CGPointMake(200, 80);
CGPoint holder3 = CGPointMake(80, 200);
CGPoint holder4 = CGPointMake(200, 200);
image1.center = holder1; //set the position of the image center to one of the newly created points
image1.alpha = 0.3; //set the image opacity back to 0.3
image2.center = holder2;
image2.alpha = 0.3;
image3.center = holder3;
image3.alpha = 0.3;
image4.center = holder4;
image4.alpha = 0.3;
}
What i'd like is to place the images randomly in the four placeholders. I have some more code written below where i get a random number between 1 and 4 and set the tag of each image to each of these random numbers.
int randomNumber;
int placeHolders[4];
int i=0;
bool numberFound;
do{ // until you get 4 unique numbers
randomNumber=arc4random()%4+1;
// Does this number exist already?
numberFound=FALSE;
for (int j=0; j<i; j++) {
if (placeHolders[j]==randomNumber)
numberFound=TRUE;
}
if (numberFound==FALSE){
placeHolders[i]=randomNumber;
i++;
}
} while (i<4);
image1.tag = placeHolders[0];
image2.tag = placeHolders[1];
image3.tag = placeHolders[2];
image4.tag = placeHolders[3];
NSLog(#"img1 tag: %i img2 tag: %i img3 tag: %i img4 tag: %i", image1.tag, image2.tag, image3.tag, image4.tag);
How do now refer to this tag information in order to move it to a placeholder?
In pseudocode i was thinking:
where image tag = 1, move that image to holder1
where image tag = 2, move that image to holder2
............
I don't know how to write this though.
If there is a better way i'd appreciate the help. Thanks
You don't need your complicated do..while / tag logic.
Just use an array:
NSMutableArray* images = [NSMutableArray arrayWithObjects: image1,image2,image3,image4,nil];
// shuffle the array
NSUInteger count = [images count];
for (NSUInteger i = 0; i < count; i++) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[images exchangeObjectAtIndex:i withObjectAtIndex:n];
}
After that, you have randomly placed your images in a new order. After that assign the positions:
UIImageView* imageView1 = (UIImageView*)[images objectAtIndex: 0];
imageView.center = holder1;
UIImageView* imageView2 = (UIImageView*)[images objectAtIndex: 1];
imageView.center = holder2;
UIImageView* imageView3 = (UIImageView*)[images objectAtIndex: 2];
imageView.center = holder3;
UIImageView* imageView4 = (UIImageView*)[images objectAtIndex: 3];
imageView.center = holder4;
(You could also do this in a loop.. so it would be more general and reusable.)

Trouble with CGRectMake

I have been trying to create a grid on the iPhone of 16x16 images.
- (void)viewDidLoad {
[super viewDidLoad];
int xLocation = 0;
for (int i=0; i <= 619; i++) {
if (((i % 30) == 0) && i != 0) { //if at end of column (30th row), moves x over 16 px to next column
xLocation += 16;
}
else {;}
CGRect imageRect = CGRectMake( xLocation, (16*i), 16, 16);
UIImageView *image = [[UIImageView alloc] initWithFrame:imageRect];
[image setImage:[UIImage imageNamed:#"Untitled-1.png"]];
[image setOpaque:YES];
NSLog(#"%d", xLocation);
[self.view addSubview:image];
[image release];
}
The problem is the int xLocation. For some reason, CGRectMake uses 0 in the x-coordinate slot instead of xLocation. I say "instead of" because the NSLog below it reveals that the xLocation has the values that I want it to, so the assignment of the values is working fine. What is going on here?
Casting xLocation as an int in your NSLog will certainly work, but you could also use:
NSLog(#"imageRect %#", NSStringFromCGRect(imageRect));
There are a whole series of NSStringFromXXX helper functions that come in handy from time to time.
The xLocation is 0 for the first column and it is being increased for each column but the y coordinate is not being reset to 0 for each new column. It just keeps increasing based on i. So the columns from the second onward are just off screen at the right xLocation but a high y value.
Try changing the imageRect calculation to:
CGRect imageRect = CGRectMake( xLocation, (16*(i % 30)), 16, 16);
%d doesn't present float's properly. Use %f or convert xLocation to an int:
NSLog(#"%d", (int)xLocation);
You can also simplify your xLocation calculation readability by calculating it each time, something like
16 * (i / 30)
The overhead is minimal on modern processors.

how to load the images in my view dynamically in a scroll view in iPhone

i want to display many images like thumbnails in a scroll view and and i want the images displayed dynamically we scrolls down or left like a table view cells
can u please tell how to that...
Thanks
with the following code..when we scroll the scroll view im calling this code and able to display the images dynamically (which r only visible) but the problem is.. while scrolling with scroll bars im getting the two images..vertically and horizontally..its only happening when i scroll.. can any body help me out please..?
int tileSize;
int imgSize;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
tileSize = 255;
imgSize = 247;
}else{
tileSize = 120;
imgSize = 116;
}
CGRect visibleBounds = [songsContainer bounds];
for (UIView *tile in [songsContainer subviews]) {
CGRect scaledTileFrame =[tile frame];
if (! CGRectIntersectsRect(scaledTileFrame, visibleBounds)) {
for(UIView *view in [tile subviews])
[view removeFromSuperview];
[recycledCells addObject:tile];
[tile removeFromSuperview];
}
}
int maxRow =[songsDict count]-1; // this is the maximum possible row
int maxCol = noOfRowsInCell-1; // and the maximum possible column
int firstNeededRow = MAX(0, floorf(visibleBounds.origin.y / tileSize));
int firstNeededCol = MAX(0, floorf(visibleBounds.origin.x / tileSize));
int lastNeededRow = MIN(maxRow, floorf(CGRectGetMaxY(visibleBounds) / tileSize));
int lastNeededCol = MIN(maxCol, floorf(CGRectGetMaxX(visibleBounds) / tileSize));
NSLog(#".........MaxRow-%d,MaxCol-%d,firstNeddedRow-%d,firstNeededcol-%d,lNR-%d,lNC%d",maxRow, maxCol, firstNeededRow,firstNeededCol,lastNeededRow,lastNeededCol);
// iterate through needed rows and columns, adding any tiles that are missing
for (int row = firstNeededRow; row <= lastNeededRow; row++) {
NSMutableArray *tempArray = (NSMutableArray *)[songsDict objectAtIndex:row];
for (int col = firstNeededCol; col <= lastNeededCol ; col++) {
BOOL tileIsMissing = (firstVisibleRow > row || firstVisibleColumn > col ||
lastVisibleRow < row || lastVisibleColumn < col);
if (tileIsMissing) {
UIView *tile = (UIView *)[self dequeueReusableTile];
if (!tile) {
// the scroll view will handle setting the tile's frame, so we don't have to worry about it
tile = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
tile.backgroundColor = [UIColor clearColor];
}
//tile.image = image for row and col;
// set the tile's frame so we insert it at the correct position
CGRect frame = CGRectMake(tileSize * col, tileSize * row, imgSize, imgSize);
tile.frame = frame;
if(col<[tempArray count])
[self addContentForTile:tile:row:col];
else tile.backgroundColor = [UIColor clearColor];
[songsContainer addSubview:tile];
}
}
}
firstVisibleRow = firstNeededRow+1; firstVisibleColumn = firstNeededCol+1;
lastVisibleRow = lastNeededRow; lastVisibleColumn = lastNeededCol;
What you have to do is create your scrollview however you want. You have to decide whether you want a grid layout, or linear layout. In addition, if grid, do you want it locked to the horizontal bounds, locked to vertical, so it scrolls either vertical or horizontal, respectively.
Once you have that sorted out, then what I recommend is taking the architecture similar to how a tableview functions. That is, create individual "cells" that will hold your thumbnails. Once you have these cells, you add them as subviews of your scrollview, at certain offsets (you need to do some math on the x/y planes).
Start with a scroll view and add each image in an UIImageView as a subview to the scrollview at a certain location.
One thing to have in mind is to only hold in memory the images that are currently shown and their immediate neighbours.

What is the best programmatically approach to display images/icons horizontally?

I'm trying to place the icons / images horizontally in a view that is intended to show details. Maximum number of pictures per row is 6 pieces and I want to have a mechanism that manage line breaks or similar automatically. I suspect it is a custom cell that solves this?
I have tried the following code below, but the images above to add another when I reload the view. Furthermore, the cell's height is not adjusted by the view that the code returned.
-(UIImageView *)fillView{
collage = nil;
collage = [[[UIImageView alloc] initWithFrame:CGRectMake(11, 7, 0, 0)] autorelease];
int rowCounter = 0;
int colCounter = 0;
int nrOfPictures = [paymentImages count];
//max 6 images per row
while (nrOfPictures > 0) {
while (colCounter <= 6 && nrOfPictures != 0) {
UIImageView *iv = [[UIImageView alloc] initWithImage:[paymentImages objectAtIndex:nrOfPictures-1]];
CGRect frame = iv.frame;
frame.origin.x = (frame.size.width + 4) * colCounter;
frame.origin.y = (frame.size.height + 4) * rowCounter;
iv.frame = frame;
[collage addSubview:iv];
[iv release];
colCounter++;
nrOfPictures--;
if (colCounter > 6) {
colCounter = 0;
rowCounter++;
}
}
}
return collage;
}
Can someone head me in the right direction?
You might want to check out this project. http://github.com/kirbyt/KTPhotoBrowser

managing images in UIScrollView

i'm not understanding where in my code i write in the image names and in what order to appear. Here is my code
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
I have images that are titled "image0.jpeg, image1.jpg." how to i insert this into my code and order them in a certain way?
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
use %d for signed int
and %u for unsigned
Your code snippet is already doing what you want - at least partially.
If you have an image numbered 0, then you need to start your loop with i = 0 instea of i = 1, and adjust the constraint appropriately:
for (NSUInteger i = 0; i < kNumImages; i++) {
NSString *imageName = [NSString stringWithFormat:#"image%u.jpg", i];
// create the image and insert into imageview
// add imageview to the containing view
}
The order is quite straight forward, as the images will be added 0, 1, 2.. and so forth
With the code from your first post, you create multiple (kNumImages, to be more specific) ImageViews, and load in them JPG files from your project directory, called "imageN.jpg", where N is integer between 1 and kNumImages.
To display these newly created views in your UIScrollView, you have to add them to it as subviews.
Something like
for (int i = 0; i < pageCount; i++) {
UIView *view = [pageViews objectAtIndex:i];
if (!view.superview)
[scrollView addSubview:view];
view.frame = CGRectMake(pageSize.width * i, 0, pageSize.width, pageSize.height);
}
The most straightforward way to do this is in UIScrollView's UIViewController. You may want to add them in some sort of collection (it's likely that the collection retains them, so don't forget to release the views, when you add them).
As you get more comfortable with your application, you may want to lazy-load the views or use simple UIViewControllers for the different images.
In iPhone OS 3.0 and above, there are significant improvements in UIScrollView, and you can find excellent code samples in the ScrollViewSuite tutorial project on ADC's iPhone section.