I am using a UIImageView to display both still and animated images. So sometimes, I'm using .image and sometimes I'm using .animationImages. This is fine.
Whether it's static or animated, I store the UIImages's in item.frames (see below)
The problem is that I'd like to display a UIActivityIndicatorView in the center of the view when the animation frames are loading. I would like this to happen with no images or frames in there. The line that isn't doing what it's supposed to is:
[self.imageView removeFromSuperview];
As a matter of fact, setting it to another image at this point doesn't do anything either. It seems like none of the UI stuff is happening in here. BTW,
NSLog(#"%#", [NSThread isMainThread]?#"IS MAIN":#"IS NOT");
prints IS MAIN.
The image that is in there will stick around until the new animation frames are all in there (1-2 seconds) and they start animating
This is all being run from a subclass of UIView with the UIImageView as a subview.
- (void)loadItem:(StructuresItem *)item{
self.imageView.animationImages = nil;
self.imageView.image = nil;
[self.spinner startAnimating];
self.item = item;
if (item.frameCount.intValue ==1){
self.imageView.image = [item.frames objectAtIndex:0];
self.imageView.animationImages = nil;
}else {
[self.imageView removeFromSuperview];
self.imageView =[[UIImageView alloc] initWithFrame:self.bounds];
[self addSubview:self.imageView ];
if( self.imageView.isAnimating){
[self.imageView stopAnimating];
}
self.imageView.animationImages = item.frames;
self.imageView.animationDuration = self.imageView.animationImages.count/12.0f;
//if the image doesn't loop, freeze it at the end
if (!item.loop){
self.imageView.image = [self.imageView.animationImages lastObject];
self.imageView.animationRepeatCount = 1;
}
[self.imageView startAnimating];
}
[self.spinner stopAnimating];
}
My ignorant assessment is that something isn't being redrawn once that image is set to nil. Would love a hand.
What I have found is not an answer to the question, but rather a much better approach to the problem. Simply, use NSTimer instead of animationImages. It loads much faster, doesn't exhaust memory and is simpler code. yay!
Do this:
-(void)stepFrame{
self.currentFrameIndex = (self.currentFrameIndex + 1) % self.item.frames.count;
self.imageView.image = [self.item.frames objectAtIndex:self.currentFrameIndex];
}
and this
-(void)run{
if (self.item.frameCount.intValue>1){
self.imageView.image = [self.item.frames objectAtIndex:self.currentFrameIndex];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1/24.0f target:self selector:#selector(stepFrame) userInfo:nil repeats:YES];
}else{
self.imageView.image = [self.item.frames objectAtIndex:0];
}
}
Related
I'm trying to create a magnet reset dot for my app, when someone clicks on the reset button it performs a reset of the hardware I use, and also flashes an orange circle from orange to green....
[NSThread detachNewThreadSelector:#selector(myMethod) toTarget:self withObject:nil];
- (void)myMethod {
UIImage *image = [UIImage imageNamed: #"orangeDot.png"];
[dot setImage: image];
sleep(1);
image = [UIImage imageNamed: #"greenDot.png"];
[dot setImage: image];
}
As you can see this occurs on a thread.
Anyway, here's my issue: The orangeDot is not being shown, even though there is a 1 second sleep?
-(void) onTick {
[self battery];
}
- (void) resetMagnet:(UIButton *) sender {
[[MySlateManager sharedManager] doReset];
if(![SettingsManager shared].isVibrationDisabled)
{
[[VibrationHelper sharedInstance]singleShortVibration];
}
NSLog(#"Testttt");
[self flickerOrange];
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 0.1
target: self
selector:#selector(onTick)
userInfo: nil repeats:NO];
}
That worked!
I have a UICollectionView displaying a bunch of images. If I don't load the images asynchronously the scrolling is very choppy and provides a poor user experience. When I load the images asynchronously the scrolling is smooth but it takes a good 5 to 10 seconds to load each image.
Why does it take so long for images to appear when loaded in the background? Here is my code for the background thread which is inside of the cellForItemAtIndexPath delegate:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImageView *bg = (id)self.backgroundView;
UIImageView *selbg = (id)self.selectedBackgroundView;
if (![bg isKindOfClass:[UIImageView class]])
bg = [[UIImageView alloc] initWithImage:thumb];
else
[bg setImage:thumb];
if (![selbg isKindOfClass:[UIImageView class]]){
selbg = [[UIImageView alloc] initWithImage:thumb];
coloroverlay = [[UIView alloc] initWithFrame:selbg.bounds];
[coloroverlay setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
[selbg addSubview:coloroverlay];
} else
[selbg setImage:thumb];
[bg setContentMode:UIViewContentModeScaleAspectFill];
[bg setTag: 1];
[coloroverlay setBackgroundColor:[col colorWithAlphaComponent:0.33f]];
[selbg setContentMode:UIViewContentModeScaleAspectFill];
dispatch_sync(dispatch_get_main_queue(), ^{
[self setBackgroundView:bg];
[self setSelectedBackgroundView:selbg];
});
});
EDIT: As #geraldWilliam pointed out, I shouldn't be accessing views from the secondary thread. Here is what I have updated my code to and fixed the issue of images getting set to the wrong cell:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImageView *bg = (id)self.backgroundView;
UIImageView *selbg = (id)self.selectedBackgroundView;
if (![bg isKindOfClass:[UIImageView class]]) bg = [[UIImageView alloc] initWithImage:thumb];
if (![selbg isKindOfClass:[UIImageView class]]){
selbg = [[UIImageView alloc] initWithImage:thumb];
coloroverlay = [[UIView alloc] initWithFrame:selbg.bounds];
[coloroverlay setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
[selbg addSubview:coloroverlay];
}
dispatch_sync(dispatch_get_main_queue(), ^{
[bg setImage:thumb];
[selbg setImage:thumb];
[bg setContentMode:UIViewContentModeScaleAspectFill];
[bg setTag: 1];
[coloroverlay setBackgroundColor:[col colorWithAlphaComponent:0.33f]];
[selbg setContentMode:UIViewContentModeScaleAspectFill];
[self setBackgroundView:bg];
[self setSelectedBackgroundView:selbg];
});
});
Most of the code you have here is fine for the main queue. The loading of the image should be on a global queue, but the rest, especially setting the image view's image, should be on the main queue. What's going on in your code is that you're dispatching back to the main queue to set the background view but leaving the assignment of the image property in the background. So, try something like:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:myImageURL]];
dispatch_sync(dispatch_get_main_queue(), ^{
imageView.image = image;
[self setBackgroundView:imageView];
});
});
I strongly recommend watching WWDC 2012 Session 211: Building Concurrent User Interfaces on iOS, which is the best WWDC session ever. It’s full of clearly presented, practical advice.
Doing stuff with UIImageView off the main queue is worrying and should be fixed, but is probably not the cause of slowness. You haven’t showed us where thumb comes from, which is likely the slow bit.
So i have a UIImageView and an NSMutuableArray of four UIImages.
I just made this UIImageView animated, all the four images are animating in this imageview in a series perfectly as it should be.
Now what i want is: When user tapped on ImageView,
Which Image is just tapped by USER.
UIImageView User Intraction is enabled
UIGestureRecognizerDelegate is Added
-(void)viewDidAppear:(BOOL)animated
{
UITapGestureRecognizer *tapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTaps:)];
tapGesture.numberOfTapsRequired = 1;
[myImageView addGestureRecognizer:tapGesture];
[self performSelectorInBackground:#selector(showAnimatedImages) withObject:nil];
[super viewDidAppear:animated];
}
- (void) showAnimatedImages
{
myImageView.animationImages = imagesArray;
myImageView.animationDuration = 12.0f;
[myImageView startAnimating];
}
- (void)handleTaps:(UITapGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateRecognized)
{
UIImage *selectedImage = [myImageView image]; // return nil
//OR
UIImage *selectedImage = myImageView.image; // return nil
//OR
NSData *imgData = UIImagePNGRepresentation(myImageView.image); // return nil
}
}
as you see myImageView.image is always giving me a nil Value.
so please tell me how can i get image from this animating imageview.
This solution will be bit different way.
Basically from the animated imageview we can't get the current image.
So do the animation in some other way
-(void)animateImages
{
count++;
[UIView transitionWithView:imageSlideshow
duration:2.0f // this is caliculated as animationduration/numberofimage
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
imageSlideshow.image = [imagesArray objectAtIndex: count % [imagesArray count]];
} completion:^(BOOL finished) {
[self animateImages];
}];
}
Now in your tap gesture you will get the image
For tap gesture not working with your edited solution, do make sure that userinteraction for your imageview is enabled and you have correctly set up the gesture for the tapgesture. If it still doesnt work then :
I am not proud of this solution and yes it is not a very good solution but if you don't find anything else you can always use this.
You can do find which image is currently selected by manually calculating that.
- (void) showAnimatedImages
{
float duration = 6;
index = 0; // declared in .h file
imageView.animationImages = imagesArray;
imageView.animationDuration = duration;
[imageView startAnimating];
float secs = duration/[imagesArray count];
// timer also declared in .h file
timer = [NSTimer scheduledTimerWithTimeInterval:secs target:self selector:#selector(changeToNextImage) userInfo:nil repeats:YES];
}
-(void)handleTaps:(UITapGestureRecognizer*)sender
{
NSLog(#"current Selected Image is at index %d",index);
}
-(void)changeToNextImage
{
index++;
if(index == [imagesArray count])
index = 0;
}
Make sure to invalidate the timer when you are done with the animations.
enter code here
if (myImageView.image){
// Image on Imageview
}else {
// Image is not available on Imageview
}
The above condition always go to else block , better follow this post
http://stackoverflow.com/questions/12858028/detect-which-image-was-clicked-in-uiimageview-with-animationimages
Thanks to everyone who tried to help me on this issue.
I am posting the solution i just found from the different suggestions on my Question and from some other posts too.
in my viewDidAppear method
-(void)viewDidAppear:(BOOL)animated
{
timer = [NSTimer scheduledTimerWithTimeInterval:6.0f target:self selector:#selector(showAnimatedImages) userInfo:nil repeats:YES];
}
and the Selector Method is
- (void) showAnimatedImages
{
if (index > [imagesArray count])
{
index = 0; // start from first index again
}
myImageView.image = [imagesArray objectAtIndex:index];
//NSLog(#"View index is = %d",index);
index ++;
}
and Tap Gesture Handling method,,, as i have only four images in Array.
- (void)handleTaps:(UITapGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateRecognized)
{
if (index == 1)
{
// do related stuff
}
else if (index == 2)
{
// do related stuff
}
else if (index == 3)
{
// do related stuff
}
else if (index == 4)
{
// do related stuff
}
}
}
before moving to next view or scene i just do
[timer invalidate];
So UIImageView Animation and Image Selection on Tap Gesture is achieved ... :)
Im attempting add image views to a UIView using this code:
for (int i = 0; i <numberOfImages; i++) {
UIImageView *image = [UIImageView alloc]initWithFrame:CGRectMake(40, 40, 40, 40)];
image.image = [images objectAtIndex:i];
[self.view addSubview:image];
}
This works but the problem is I would like to have a 5 second delay before it adds each image, instead it adds them all at the same time. Can anybody help me out? Thanks.
Example:
5 seconds = one image on screen
10 seconds = two images on screen
15 seconds = three images on screen
It will be more efficient to use an NSTimer.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:numberOfSeconds
target:self
selector:#selector(methodToAddImages:)
userInfo:nil
repeats:YES];
This will essentially call methodToAddImages repeatedly with the specified time interval. To stop this method from being called, call [NSTimer invalidate] (bear in mind that an invalidated timer cannot be reused, and you will need to create a new timer object in case you want to repeat this process).
Inside methodToAddImages you should have code to go over the array and add the images.
You can use a counter variable to track the index.
Another option (my recommendation) is to have a mutable copy of this array and add lastObject as a subview and then remove it from the mutable copy of your array.
You can do this by first making a mutableCopy in reversed order as shown:
NSMutableArray* reversedImages = [[[images reverseObjectEnumerator] allObjects] mutableCopy];
Your methodToAddImages looks like:
- (void)methodToAddImages
{
if([reversedImages lastObject] == nil)
{
[timer invalidate];
return;
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:(CGRectMake(40, 40, 40, 40))];
imageView.image = [reversedImages lastObject];
[self.view addSubview:imageView];
[reversedImages removeObject:[reversedImages lastObject]];
}
I don't know if you're using ARC or Manual Retain Release, but this answer is written assuming ARC (based on the code in your question).
You can use dispatch_after to dispatch a block, executed asynchronously that adds the image. Example:
for(int i = 0; numberOfImages; i++)
{
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
UIImageView *image = [UIImageView alloc]initWithFrame:CGRectMake(40, 40, 40, 40)];
image.image = [images objectAtIndex:i];
// Update the view on the main thread:
[self.view performSelectorOnMainThread: #selector(addSubview:) withObject: image waitUntilDone: NO];
});
}
Separate your code into a function, and call via NSTimer.
for (int i = 0; numberOfImages; i++) {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:#selector(showImage)
userInfo:[NSNumber numberWithInt:i]
repeats:NO];
And then your function:
-(void) showImage:(NSTimer*)timer {
//do your action, using
NSNumber *i = timer.userInfo;
//Insert relevant code here
if (!done)
NSTimer *newTimer = [NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:#selector(showImage)
userInfo:[NSNumber numberWithInt: i.intValue+1]
repeats:NO];
}
}
userInfo is a convenient way of passing parameters to functions that you need to call (but they do have to be Objects). Also, by using repeats:NO, you don't have to worry about invalidating the timer, and there's no risk of leaving timer running in memory.
also this is best option. Try this
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];
I think you'd be better off with an animation
for (int i = 0; i < numberOfImages; i++)
{
// Retrieve the image
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
image.image = [images objectAtIndex:i];
// Add with alpha 0
image.alpha = 0.0;
[self.view addSubview:image];
[UIView animateWithDuration:0.5 delay:5.0*i options:UIViewAnimationOptionAllowUserInteraction animations:^{
// Fade in with delay
image.alpha = 1.0;
} completion:nil];
}
Not exactly what you asked for, since all the views will be added immediately, and then faded-in, but I feel that you're actually trying to achieve that, like some sort of stacking of images, right?
In fact, if you plan on removing the previous image, you can do it in the completion block, like this:
UIImageView *imagePrevious = nil;
for (int i = 0; i < numberOfImages; i++)
{
// Retrieve the image
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
image.image = [images objectAtIndex:i];
// Add with alpha 0
image.alpha = 0.0;
[UIView animateWithDuration:0.5 delay:5.0*i options:UIViewAnimationOptionAllowUserInteraction animations:^{
// Add and fade in with delay
[self.view addSubview:image];
image.alpha = 1.0;
} completion:^(BOOL finished)
{
if (finished && imagePrevious)
{
[imagePrevious removeFromSuperview];
}
}];
imagePrevious = image;
}
I have an animation that is not animating for some reason.
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.hidden = YES;
self.nameLabel.text = [self.name uppercaseString];
self.gradient1.alpha = .9;
self.gradient1.image = [UIImage imageNamed:#"heart.png"];
self.gradient1.animationImages = [[NSArray alloc] initWithObjects:
[UIImage imageNamed:#"gradiant1.png"],
[UIImage imageNamed:#"gradiant2.png"],
...
[UIImage imageNamed:#"gradiant26.png"], nil];
self.gradient1.animationDuration = .5;
self.gradient1.animationRepeatCount = 1;
[self updateStats:nil];
}
-(void)updateStats:(NSTimer*)timer{
Utilities *utility = [[Utilities alloc] init];
[utility getDataWithSSID:self.ssID completion:^(bool *finished, NSArray *objects) {
if (finished){
...
[self.gradient1 startAnimating];
}
self.twoSecTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self
selector:#selector(updateStats:)
userInfo:nil
repeats:NO];
}];
}
Sometimes it animates once or twice and then stops even though the timer continues to hit over and over. Other times it just doesn't animate at all. However, I have a couple placeholder buttons that I put on the storyboard that aren't tied to anything and whenever I press one of the buttons it animates the next time the timer hits (Actually whenever I hit the screen even though I don't have any sort of gesture recognizers..). Also, when I add in all the other garbage I want to do in this ViewController it animates every other time it's being called. So I think it's something deeper than me forgetting so set some property.
It might be a better idea to move the animation trigger to a moment when that view is actually visible - hence to viewDidAppear:.
Also your way of creating a recursive timer scheduling makes me shiver. I guess it works fine for you but I would definitely suggest to use the repeats flag set to YES instead.
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.hidden = YES;
self.nameLabel.text = [self.name uppercaseString];
self.gradient1.alpha = .9;
self.gradient1.image = [UIImage imageNamed:#"heart.png"];
self.gradient1.animationImages = [[NSArray alloc] initWithObjects:
[UIImage imageNamed:#"gradiant1.png"],
[UIImage imageNamed:#"gradiant2.png"],
...
[UIImage imageNamed:#"gradiant26.png"], nil];
self.gradient1.animationDuration = .5;
self.gradient1.animationRepeatCount = 1;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
//animate right away...
[self updateStats:nil];
//trigger new animations every two seconds
self.twoSecTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self
selector:#selector(updateStats:)
userInfo:nil
repeats:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self stopUpdatingStats];
}
-(void)stopUpdatingStats
{
[self.twoSecTimer invalidate];
}
-(void)updateStats:(NSTimer*)timer
{
NSLog(#"updating");
[self.gradient1 startAnimating];
}