Flipping a UIImage horizontally in UIImageView - ios

In my project, I have my image files stored in jpeg format. The code below "works" in that it doesn't crash, but my images don't flip when they're supposed to. I threw a breakpoint in to ensure that the code is running--it is, but the images that are displayed aren't flipped. I'm guessing I'm missing something basic, but it's not jumping out at me.
if (self.isTimer == YES) {
// this is where images get dumped if they exist
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int imageNumber = 1; self.currentItem.photo != nil; imageNumber++) {
NSString *fileName = [NSString stringWithFormat:#"%#-%d", self.currentItem.photo, imageNumber];
if ([UIImage imageNamed:fileName]) {
UIImage *image = [UIImage imageNamed:fileName];
// test whether count is even or odd
if (self.currentItem.sideMultiplier.intValue == 1) {
// if there's only one side to be done, dump unflipped images in array
[imageArray addObject:image];
NSLog(#"regular image added to array");
} else {
// if there are 2 sides, determine if it's even or odd side
if (self.stretchSideMultiplierCount % 2 == 1) {
// add a unflipped image to the array
[imageArray addObject:image];
NSLog(#"regular image added to array");
} else {
// ** I want to add a FLIPPED IMAGE here
UIImage *flippedImage = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:UIImageOrientationUpMirrored];
[imageArray addObject:flippedImage];
NSLog(#"flipped image added to array");
}
}
NSLog(#"%# added to imageArray", fileName);
} else {
break;
}
}
I followed this post, but nothing's happening.
How to flip UIImage horizontally?
I added #import <QuartzCore/QuartzCore.h> to my implementation file. Aside from that, I'm out of ideas re: how to flip an image horizontally.
UPDATE: Much easier solution
Rather than flipping the UIImage, I flipped the UIImageView. The code above I used to create my imageArray now looks like this:
if (self.isTimer == YES) {
// this is where images get dumped if they exist
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int imageNumber = 1; self.currentItem.photo != nil; imageNumber++) {
NSString *fileName = [NSString stringWithFormat:#"%#-%d", self.currentItem.photo, imageNumber];
if ([UIImage imageNamed:fileName]) {
UIImage *image = [UIImage imageNamed:fileName];
[imageArray addObject:image];
NSLog(#"image added to array");
NSLog(#"%# added to imageArray", fileName);
} else {
break;
}
}
and the code I used to flip my UIImageView is in the answer below.

Problem solved. Rather than flipping the UIImage, I flipped the UIImageView as follows:
self.myImageView.transform = CGAffineTransformMakeScale(-1, 1);

Related

NSArray [UIImage setContentMode:]

I want to put defaults images if i don't have images from url feed.
if(![[stories objectAtIndex:storyIndex] valueForKey:#"url"]==nil)
{ NSNumber *numberOfKeyInstances = [stories valueForKey:#"key"];
imageArray=[NSArray arrayWithObjects:[UIImage imageNamed:#"1.png"],nil];
int randomNumber_ = rand ()%19;
UIImage *image = [imageArray objectAtIndex:indexPath.row];
cell.imag=image;
}
else{
if (![[[stories objectAtIndex:storyIndex] valueForKey:#"url"] isEqualToString:#""]) {
[cell.imag setImageWithURL:[NSURL URLWithString:[[stories objectAtIndex:storyIndex] objectForKey:#"url"]] placeholderImage:[UIImage imageNamed:#"Alb.png"]];
}
}
This is my code, but i get [UIImage setContentMode:]: unrecognized selector sent to instance 0x7f908c1dcce0'
How can i solved?
Firstly, imageArray is initialised with only one image. So calling [imageArray objectAtIndex:indexPath.row] is a problem. You dont need an image array for that. Secondly, the argument inside the first if statement doesn't look right.
Also, as #midhun-mp Pointed out, u should be probably using cell.imag.image.
Try this :
if([[stories objectAtIndex:storyIndex] valueForKey:#"url"] == nil)
{
cell.imag.image = [UIImage imageNamed:#"1.png"];
}
else if ([[[stories objectAtIndex:storyIndex] valueForKey:#"url"] isEqualToString:#""])
{
cell.imag.image = [UIImage imageNamed:#"1.png"];
}
else
{
//SET YOUR IMAGE HERE
}
Try to change
UIImage *image = [imageArray objectAtIndex:indexPath.row];
to
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:[imageArray objectAtIndex:indexPath.row]]];
I suspect that cell.imag is a UIImageView not UIImage property.
So you need to change:
cell.imag=image;
to
cell.imag.image = image;

Issue using displaying Image with NSMutableArray

I am very new to xcode and I am playing around with image arrays and NSMutableArray. When I run the code below it just print out the names of the image for example "image1.png". Any tips to fix this problem would be appreciated. Thanks.
- (NSMutableArray*)restaurantArray;
{
if (_restaurantArray == nil) {
_restaurantArray = [[NSMutableArray alloc] initWithObjects:
#"image1.png",
#"image2.png",
#"image3.png",
nil];
}
return _restaurantArray;
}
-(NSString*) randomRestaurant
{
int random = arc4random_uniform(self.restaurantArray.count);
return [self.restaurantArray objectAtIndex:random];
}
You could do it in this way also.
- (NSMutableArray*)restaurantArray;
{
if (_restaurantArray == nil) {
_restaurantArray = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:#"image1.png"],
[UIImage imageNamed:#"image2.png"],
[UIImage imageNamed:#"image3.png"],
nil];
}
return _restaurantArray;
}
Do you mean this?:
NSString *imageName = [self randomRestaurant];
UIImage *image = [UIImage imageName:imageName];
If you want to display the image then do this:
Suppose you have an imageview name imgView,
imgView.image = [UIImage imageNamed:[self randomRestaurant]];
Or, if you just want the image, then call this:
UIImage *img = [UIImage imageNamed:[self randomRestaurant]];
In you given code, you are just returning the name of the image, not the actual image. If you want an array of image then you can do it by this way:
-(NSMutableArray*) restaurantArray;
{
if (_restaurantArray == nil) {
UIImage *img = [UIImage imageNamed:#"image1.png"];
UIImage *img1 = [UIImage imageNamed:#"image2.png"];
UIImage *img2 = [UIImage imageNamed:#"image3.png"];
_restaurantArray = [[NSMutableArray alloc] initWithObjects:
img,
img1,
img2,
nil];
}
return _restaurantArray;
}
-(UIImage*) randomRestaurant
{
int random = arc4random_uniform(self.restaurantArray.count);
return [self.restaurantArray objectAtIndex:random];
}
Hope this helps.. :)

Parse.com Saving images sample. retrieve only one image

I have set up the sample from parse.com where you can upload an image from the camera and then display all the images in a grid view.
What I want is to display only the recent image taken instead of a total grid view.
The sample is located here : Parse example
The images is being downloaded and placed in some sort of grid view.
The use NSMutableArray *allImages; to get all the images.
The images is being output with button classes and a link to a new view.
The new view then only contains the image from the grid view (the one you click).
I would like to instead of downloading all of the images and placing them inside a grid view - just to display the latest image.
They code used to take the image from a small thumbnail to the full image view is like this:
// When picture is touched, open a viewcontroller with the image
PFObject *theObject = (PFObject *)[allImages objectAtIndex:[sender tag]];
PFFile *theImage = [theObject objectForKey:#"imageFile"];
NSData *imageData;
imageData = [theImage getData];
UIImage *selectedPhoto = [UIImage imageWithData:imageData];
PhotoDetailViewController *pdvc = [[PhotoDetailViewController alloc] init];
pdvc.selectedImage = selectedPhoto;
[self presentViewController:pdvc animated:YES completion:nil];
The code to get allImages is like:
// Contains a list of all the BUTTONS
allImages = [images mutableCopy];
// This method sets up the downloaded images and places them nicely in a grid
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSMutableArray *imageDataArray = [NSMutableArray array];
// Iterate over all images and get the data from the PFFile
for (int i = 0; i < images.count; i++) {
PFObject *eachObject = [images objectAtIndex:i];
PFFile *theImage = [eachObject objectForKey:#"imageFile"];
NSData *imageData = [theImage getData];
UIImage *image = [UIImage imageWithData:imageData];
[imageDataArray addObject:image];
}
// Dispatch to main thread to update the UI
dispatch_async(dispatch_get_main_queue(), ^{
// Remove old grid
for (UIView *view in [photoScrollView subviews]) {
if ([view isKindOfClass:[UIButton class]]) {
[view removeFromSuperview];
}
}
// Create the buttons necessary for each image in the grid
for (int i = 0; i < [imageDataArray count]; i++) {
PFObject *eachObject = [images objectAtIndex:i];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [imageDataArray objectAtIndex:i];
[button setImage:image forState:UIControlStateNormal];
button.showsTouchWhenHighlighted = YES;
[button addTarget:self action:#selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
button.frame = CGRectMake(THUMBNAIL_WIDTH * (i % THUMBNAIL_COLS) + PADDING * (i % THUMBNAIL_COLS) + PADDING,
THUMBNAIL_HEIGHT * (i / THUMBNAIL_COLS) + PADDING * (i / THUMBNAIL_COLS) + PADDING + PADDING_TOP,
THUMBNAIL_WIDTH,
THUMBNAIL_HEIGHT);
button.imageView.contentMode = UIViewContentModeScaleAspectFill;
[button setTitle:[eachObject objectId] forState:UIControlStateReserved];
[photoScrollView addSubview:button];
}
// Size the grid accordingly
int rows = images.count / THUMBNAIL_COLS;
if (((float)images.count / THUMBNAIL_COLS) - rows != 0) {
rows++;
}
int height = THUMBNAIL_HEIGHT * rows + PADDING * rows + PADDING + PADDING_TOP;
photoScrollView.contentSize = CGSizeMake(self.view.frame.size.width, height);
photoScrollView.clipsToBounds = YES;
});
});
I'm not an expert at this iOS-coding and I'm really just looking for a simple solution to display the recent image posted.
Looking through the posted example code, it would be a big undertaking to modify it to handle just a one image (mostly deleting a lot of yuck that synchs object ids). If you just want the quickest path to get started, you can do this:
// ...
// where you do the query for UserPhoto
[query orderByAscending:#"createdAt"];
// use the getFirst form of the query
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
// build the objects array that the demo code expects, but out of just one object
NSArray *objects = #[ object ];
// the remainder of the code as it is
A lot of UI code can get simpler, too. But the key is to skip all of the grid/button building code and do something like this:
// ...
// inside the method called setUpImages:
// this loop will only run once since we have only one object in the array
for (int i = 0; i < [imageDataArray count]; i++) {
PFObject *eachObject = [images objectAtIndex:i];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [imageDataArray objectAtIndex:i];
// you're essentially done here. add a big image view
// that replaces photoScrollView, then:
self.myBigImageView.image = image;
Hope that helps.

Need to see which UIImageView is empty and place an image there

Here's my problem. I have 3 UIImageViews that are empty by default, placed on a UIView that are is hidden at first.
And they are supposed to be filled one after another when a user selects something.
I know it sounds confusing, but I think my code below will clear things out:
- (IBAction)selectButtonPressed:(id)sender {
if ([labelText.text isEqualToString:#"some text"]) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"someImage"] ofType:#"png"];
UIImage * image = (UIImage * )[UIImage imageWithContentsOfFile:filePath];
if (firstImage.image == nil) {
firstImage.image = image;
imagesView.hidden = YES;
firstImage.hidden = NO;
} // places it in the first Image View if it's empty ...
else if (secondImage.image == nil) {
secondImage.image = image;
imagesView.hidden = YES;
secondImage.hidden = NO;
} // ... or in the second one if empty
else {
thirdImage.image = image;
imagesView.hidden = YES;
thirdImage.hidden = NO; // ... else in the third one
}
[filePath release];
[image release];
}
// then does the same thing depending on the users selection.
else if ([labelText.text isEqualToString:#"some other text"]) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"someOtherImage"] ofType:#"png"];
UIImage * image = (UIImage * )[UIImage imageWithContentsOfFile:filePath];
if (firstImage.image == nil) {
firstImage.image = image;
imagesView.hidden = YES;
firstImage.hidden = NO;
}
else if (secondImage.image == nil) {
secondImage.image = image;
imagesView.hidden = YES;
secondImage.hidden = NO;
}
else {
thirdImage.image = image;
imagesView.hidden = YES;
thirdImage.hidden = NO;
}
[filePath release];
[image release];
}
// and same thing below if none of the above.
else {
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"yet another text"] ofType:#"png"];
UIImage * image = (UIImage * )[UIImage imageWithContentsOfFile:filePath];
if (firstImage.image == nil) {
firstImage.image = image;
imagesView.hidden = YES;
firstImage.hidden = NO;
}
else if (secondImage.image == nil) {
secondImage.image = image;
imagesView.hidden = YES;
secondImage.hidden = NO;
}
else {
thirdImage.image = image;
imagesView.hidden = YES;
thirdImage.hidden = NO;
}
[filePath release];
[image release];
} // Code for checking which Image View is empty and place the image there.
}
So, it launches and works fine, when I do the first selection. But for the 2nd one it says EXC_BAD_ACCESS and crashes. Sometimes it works for the first 2 selections and for the third one it crashes.
Please let me know if it's confusing, I'll try to explain my intent as clear as I can.
Thanks a lot
UPDATE: Well, I think it's true that an answer appears when you ask the right question.
Everything worked well, after I've used firstImage.image = [UIImage imageNamed:#"someImage"]; instead of the whole NSBundle method. Code became cleaner and works like a charm.
However I'm not sure if there are any downsides to this. So if you guys can warn me of anything, I'm all opened to that.
Thanks again.
Your problem probably related to your memory management. Did you use property for those imageview? Also, you don't need to release filePath and image because you did not use the alloc, etc. method to initialize it.

How do I remove an UIImageView animation from memory completely?

I'm trying to free up my apps memory and want to completely remove loadingImageView from memory when I tap a button. How do I do this?
-(IBAction)animationOneStart {
NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:88];
for(int count = 1; count <= 88; count++)
{
NSString *fileName = [NSString stringWithFormat:#"testPic1_%03d.jpg", count];
UIImage *frame = [UIImage imageNamed:fileName];
[images addObject:frame];
}
loadingImageView.animationImages = images;
loadingImageView.animationDuration = 5;
loadingImageView.animationRepeatCount = 1; //Repeats indefinitely
[loadingImageView startAnimating];
[images release];
}
-(IBAction)removeFromMemory {
//What do I add here?
}
Thanks!
Ok. If you want to remove UIImageView animation try this:
-(IBAction)removeFromMemory {
[loadingImageView stopAnimating]; //here animation stops
[loadingImageView removeFromSuperview]; // here view removes from view hierarchy
[loadingImageView release]; loadingImageView = nil; //clean memory
}
For remove CoreAnimation from UIView instance use method:
[view.layer removeAllAnimations];

Resources