using integer variable to image name in ios - ios

I have a set of images named 0.png, 1.png, 2.png, etc...
Say I only have five. I want to use an integer variable (infoInt) to determine what image is displayed. Since I'm naming the images in numbers, I though I could define the image as what ever the integer was. i.e. infoInt.png (as infoInt changes). I'm not sure how I can approach it. Here is my attempt.
- (void)viewDidLoad{
[super viewDidLoad];
UIImage *img;
for (infoInt =0; infoInt<=5; infoInt++) {
img = [UIImage imageNamed:infoInt".png"]; //What to do here? How do I use infoInt variable in image name?
[imageView setImage:img];
}

You can use +[NSString stringWithFormat:] to construct the name, as in
img = [UIImage imageNamed:[NSString stringWithFormat:#"%d.png", infoInt]];

Change this line
img = [UIImage imageNamed:infoInt".png"];
to
img = [UIImage imageNamed:[NSString stringWithFormat:#"%d.png",infoInt]];
Hope it helps you

You can use stringWithFormat and use the for loop counter to generate image name as
img = [UIImage imageNamed:[NSString stringWithFormat:#"%d.png", infoInt]];

Use:
NSString *fileName = [NSString stringWithFormat:#"%d.png", infoInt]
img = [UIImage imageNamed:fileName];
Also refer NSString Class Reference for more string functions.

Related

UIImage from file always nil

I am making a document scanning app
the document that is scanned is stored in a temp file within the application structure and the path of this file stored in a NSString variable
This image is passed to a UIImageView which successfully loads
[self.cameraViewController captureImageWithCompletionHander:^(NSString *imageFilePath)
{
UIImageView *captureImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:imageFilePath]];
captureImageView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];
captureImageView.frame = CGRectOffset(weakSelf.view.bounds, 0, -weakSelf.view.bounds.size.height);
captureImageView.alpha = 1.0;
captureImageView.contentMode = UIViewContentModeScaleAspectFit;
captureImageView.userInteractionEnabled = YES;
[weakSelf.view addSubview:captureImageView];
Then want to convert the image to base64 ready for upload. In order to do this i will call the following which accepts a UIImage object
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
The value of the imageFilePath variable is
/private/var/mobile/Containers/Data/Application/79C28B96-275D-48F1-B701-CABD699C388D/tmp/ipdf_img_1447880304.jpeg
To fetch the image from the file i used this
UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageFilePath ofType:nil]];
base64String = [self encodeToBase64String:img];
The problem is that the UIImage object is always nill (or nill). At first i though that the problem could be the path, but the image loads within the UIImageView.
Can someone please help me with the figuring out why this does not return the image stored within the imageFilePath variable
Replace:
UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageFilePath ofType:nil]];
with:
UIImage *img = [UIImage imageWithContentsOfFile:imageFilePath];
You are not loading the image from the bundle.
Also, make sure you are not trying to use the full path across executions of the app. Only persist relative paths since the path to the app's sandbox can change over time.

NSMutableArray creates issue for images

I have an array with dictionaries in it. Each dictionary contains UIImage & String values.
But when I try to delete object using
[arr removeObjectAtIndex:button.tag];
then it just decreases the count but image (Object) is not deleted.
So, my Images are overlapping when try to delete.
It also creates problem when I try to add objects in the array
[arr insertObject:dict atIndex:0];
so, I used
[_postObj.arr_images addObject:dict]; instead of insertObject
Help me to solve this
Objects use reference counting and both NSMutableArray and UIImageView will retain the UIImage object.
This means that removing it from the array will not automatically remove it from the UIImageView and you must remove it from both explicitly:
[arr removeObjectAtIndex:button.tag];
_imageView.image = nil;
Problem is in your frame setting of UIImageView. Please try using below code (not tested by myself) and see if this fixes the issue for you. Basically, I am adjusting X position of images based on previous image's width.
CGFloat imageXM = 5.0;
CGFloat imageXPos = 0;
for (UIImage *image in arr_images) {
CGRect imageFrame = CGRectMake(imageXPos + imageXM, 0.0, image.size.width, image.size.height);
imageXPos = imageXPos + image.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageFrame];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image = image;
[scl addSubview:imageView];
}
As in your code
[picker dismissViewControllerAnimated:YES completion:^{
[arr_images insertObject:chosenImage atIndex:0];
[self scrollImages_Setup2];
}];
[arr_images insertObject:chosenImage atIndex:0]; that means you need only one image to display on scroll view. Then why you take a loop:
-(void)scrollImages_Setup2
{
for (int k=0; k<arr_images.count; k++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(scl.frame) * k) + CGRectGetWidth(scl.frame), 0, CGRectGetWidth(scl.frame), CGRectGetHeight(scl.frame))];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image=[arr_images objectAtIndex:k] ;
[scl addSubview:imageView];
}
scl.contentSize = CGSizeMake((CGRectGetWidth(scl.frame) * arr_images.count)+CGRectGetWidth(scl.frame), CGRectGetHeight(scl.frame));
}
You just right the code only for display the Image. you don't need to scroll view for displaying only one image. I think you are not clear what you want.
Your problem regarding the overwriting the images because of loop. so remove the loop, when you display a single image. Please remove the scrollview contentSize, because image_array will increase, when you add the multiple images in array and size width will be large. so remove arr_images.count as well.

Using a String as Images Name

I am working on a while loop that spits out 30 images, each image having a different name. The way I approached this was by creating a NSString variable call img, which will be different with each iteration, i.e., "Badguy 1", "Badguy 2", ect... Then using that string as the name of the image being created.
TotalShips = 1
while(TotalShips < 31){
img = [NSString stringWithFormat:#"Badguy %i",TotalShips];
UIImageView *img = [[UIImageView alloc] initWithFrame: CGRectMake(10,20,20,20)];
img.image = [UIImage imageNamed:#"Badguy.png"];
[self.view addSubview: img];
TotalShips = TotalShips + 1;
}
This doesn't seem to work, and I haven't found very much help on changing an image's name.
Thanks,
Alex
The UIImageView has an property animatedImages (NSArray). Vou can easily play auround with animationDuration and animationReapCount. You can start the animation with [myImageView startAnimation] and stop with [myImageView stopAnimation].
Please read: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImageView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006889-CH3-SW3
The file names can you build in a loop with 'NSString *fileName = [NSString stringWithFormat:#"image%i.png",imageName, iterator]'.
Not sure what you're trying to do, but I'll try to explain what your code does, maybe it helps you understand the problem:
TotalShips = 1
while(TotalShips < 31){
// here your img variable is a string, which will be 'Badguy 1', 'Badguy 2', etc
// you're not using this img value set here anywhere else in your code
img = [NSString stringWithFormat:#"Badguy %i",TotalShips];
// here you redeclare your img as an UIImageView
UIImageView *img = [[UIImageView alloc] initWithFrame: CGRectMake(10,20,20,20)];
// here you assign the image in the imageView to the image 'Badguy.png'
img.image = [UIImage imageNamed:#"Badguy.png"];
[self.view addSubview: img];
TotalShips = TotalShips + 1;
}
So, your code creates 30 different UIImageViews , all of them with the same image: 'Badguy.png', and adds them one on top of the other to the current view. I suppose this is not what you wanted to do.

UIImagePickerControllerEditedImage get nil

Hey guys I'm doing some image editing with UIImagePickerController. Here is some code in imagePickerController:didFinishPickingMediaWithInfo:
UIImage *editedImg = [info objectForKey:UIImagePickerControllerEditedImage];
UIImageView *imgView = [[UIImageView alloc] initWithImage:editedImg];
CGRect imgFrm = imgView.frame;
float rate = imgFrm.size.height / imgFrm.size.width;
imgFrm.size.width = size;
imgFrm.size.height = size * rate;
imgFrm.origin.x = 0;
imgFrm.origin.y = (size - imgFrm.size.height) / 2;
[imgView setFrame:imgFrm];
UIView *cropView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size, size)];
[cropView setBackgroundColor:[UIColor blackColor]];
[cropView addSubview:imgView];
UIImage *croppedImg = [MyUtil createUIImageFromUIView:cropView];
The above is to set the image in a size*size view and draw a image from a view when the height of the image returned by picker is smaller than size.
Here is the code of createUIImageFromUIView:(UIView*)view :
+ (UIImage *)createUIImageFromUIView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 2.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
My problem is : when debugging, the 'editedImg'(defined in first line) just shows 'nil'. But, the following code works well. I get the corpView(shows 'nil' too) correctly and get cropped image and can encode it to base64 encoded string for sending to server side. I just want to know why the editedImg is nil(returned by [info objectForKey:UIImagePickerControllerEditedImage], but when I choose to print the info in debug mode, the output is not nil in the console)?
The editdImg gets nil, try:
UIImage *editedImg = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
Get file sizeļ¼š
- (long long) fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
Best wishes!
After some searching I accidentally found this : string value always shows nil in objective-c
This is the reason why I always see 'nil' in debug mode while the code works well.
You can get your cropped image size by
UIImage *croppedImg = [MyUtil createUIImageFromUIView:cropView];
NSData *dataForImage = UIImagePNGRepresentation(croppedImg);
Now you can check length
if (dataForImage.length)
{
}

Can you display a small image in a detailTextLabel cell?

So I was wondering if it is possible to display a small image in a detailTextLabel of a cell? (I'm getting the image from a URL) I tried it with:
NSString *thumbs = [NSString stringWithFormat:#"%#", TableText3];
cell.detailTextLabel.text = thumbs;
Which for obvious reason doesn't work. I also tried with:
UIImage *thumbs = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:TableText3]]];
cell.detailTextLabel.text = thumbs;
Which also (obviously) doesn't work, because I'm passing an image to a string parameter.
Surprisingly I didn't find anything on the WWW. (Search parameters were: "image in detailTextLabel" or picture or just textlabel and image and various variations)
You can't put it directly into the label because labels only display text. But you can use the imageView property of the UITableViewCell.
cell.imageView = [[UIImageView alloc] initWithImage: thumbs];
https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html
Rather than putting the image in the imageView property, you could create an UIImageView and place it in the accessoryView property:
UIImage * thumbs;
UIImageView * thumbsView;
CGFloat width;
thumbs = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:TableText3]]];
thumbsView = [[[UIImageView alloc] initWithImage:thumbs] autorelease];
width = (cell.frame.size.height * thumbs.size.width) / thumbs.size.height;
thumbsView.frame = CGRectMake(0, 0, width, cell.frame.size.height);
cell.accessoryView = thumbsView;
This will size the image to fit within the cell and position it to the right of the textLabel and detailTextLabel.
A better approach is not to rely on the built-in UITableViewCell types and create your own cell frame and add all the labels, view, images at your desired position inside the cell. Then you can return the cell for your tableview.

Resources