Preloading a UIImageView animation using objective c for the iphone - iphone

I have an animated image which works great. It consists of 180 high quality images and it plays fine and loops continuously. My problem is that the first time I load the view containing these images it takes a long time to load. Every subsequent time after that it loads immediately as I am assuming that the images have been cached or preloaded!!! I come from a flash background and as I am sure you aware preloaders are as common as muck so I don't feel this should be difficult to find but after countless googling I cannot find any good examples on preloading or any articles on why there is a delay and what to do about it.
So my question(s) is this:
Is there a checkbox in the info.plist to preload all my images at the start of the app?
How can you preload images and are there any simple example projects that I could look at?
Is this the best way to implement what is essentially a video but has been output to a png sequence?
Is there another method as viewDidLoad does not work as I expect it to do. It traces "FINISHED LOADING IMAGES" (see code below) but the view does not show for a second or two after the images have been loaded so if the view does not show until the images have loaded then neither will the UIActivityIndicatorView which is also in the same view.
How do you do event listening in objective c?
Below is the code in the viewDidLoad which I believe is fairly standard:
Any help is greatly appreciated as I am banging my head on a brick wall on something that seems so basic in ui development. Help :)
- (void)viewDidLoad {
[super viewDidLoad];
imageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT];
NSLog(#"START LOADING IMAGES");
// Build array of images, cycling through image names
for (int i = 0; i < IMAGE_COUNT; i++){
[imageArray addObject:[UIImage imageNamed: [NSString stringWithFormat:#"Main_%d.png", i]]];
}
animatedImages = [[UIImageView alloc] initWithFrame:CGRectMake(0,20,IMAGE_WIDTH, IMAGE_HEIGHT)];
animatedImages.animationImages = [NSArray arrayWithArray:imageArray];
animatedImages.animationDuration = 6.0;
animatedImages.animationRepeatCount = 0;
[self.view addSubview:animatedImages];
animatedImages.startAnimating;
[animatedImages release];
NSLog(#"FINISH LOADING IMAGES");
}
Cheers
M

In case someone finds this question, I have an answer, which is to pre-render the images like this.
NSMutableArray *menuanimationImages = [[NSMutableArray alloc] init];
for (int aniCount = 1; aniCount < 21; aniCount++) {
NSString *fileLocation = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat: #"bg%i", aniCount + 1] ofType: #"png"];
// here is the code to load and pre-render the image
UIImage *frameImage = [UIImage imageWithContentsOfFile: fileLocation];
UIGraphicsBeginImageContext(frameImage.size);
CGRect rect = CGRectMake(0, 0, frameImage.size.width, frameImage.size.height);
[frameImage drawInRect:rect];
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// then add the resulting image to the array
[menuanimationImages addObject:renderedImage];
}
settingsBackground.animationImages = menuanimationImages;
I have tried multiple other methods of pre-loading images, and this is the only thing I've found that works.

My problem is that the first time I load the view containing these images it takes a long time to load. Every subsequent time after that it loads immediately as I am assuming that the images have been cached or preloaded
you are right at this point ...... as you are using method imageNamed: for this method document quotes.....
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
so in my opinion, rather than doing following stuff in viewDidLoad, you should do it earlier where delay is of not considerable......
for (int i = 0; i < IMAGE_COUNT; i++)
{
[imageArray addObject:[UIImage imageNamed: [NSString stringWithFormat:#"Main_%d.png", i]]];
}
another approach
- (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration
direction:(int)direction
{
CABasicAnimation* rotationAnimation;
// Rotate about the z axis
rotationAnimation =
[CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
// Rotate 360 degress, in direction specified
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 * direction];
// Perform the rotation over this many seconds
rotationAnimation.duration = inDuration;
rotationAnimation.repeatCount = 100;
//rotationAnimation.
// Set the pacing of the animation
//rotationAnimation.timingFunction =
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// Add animation to the layer and make it so
[inLayer addAnimation:rotationAnimation forKey:#"rotationAnimation"];
}
this method will help in animation call it as follow(I am assuming that you are putting above method in same class where you have imageView.
[self spinLayer:yourImageView.layer duration:5.0
direction:<-1 or 1 for anti clockwise or clockwise spin>];
remember just set only one image to that imageView(which you wish to animate.
thanks,

Related

Displaying Multiple CALayers one after another continuously for 60 seconds?

I have a situation over here.
I am using AVFoundation to capture the camera frame.
Now what i want to do is that for certain frames, i need to display a picture which revolves in a step by step fashion.
What I am trying to do is that I am taking 4 CALayers comprising of front back left and right images of an object and using CALayer time property and group animation property, i want to display all the images one by one after certain milli seconds interval of time so that the continuous images seems to be like an animation.
How to go about it ? Please help me with some coding here.
-(void)startMainAnimation
{
//Animationframes is array of images that should be CGImage Type not UIImage..
//animation Layer that is added above view……
CAKeyframeAnimation *frameAnimation = [[CAKeyframeAnimation alloc] init];
[frameAnimation setKeyPath:#"contents"];
frameAnimation.calculationMode = kCAAnimationDiscrete;
[animationLayer setContents:[animationFrames lastObject]];
frameAnimation.autoreverses = NO;
frameAnimation.duration = ((float)[animationFrames count])/4.5;;
frameAnimation.repeatCount = 1;
[frameAnimation setValues:animationFrames];
[frameAnimation setRemovedOnCompletion:YES];
[frameAnimation setDelegate:self];
[animationLayer addAnimation:frameAnimation forKey:#"contents"];
[frameAnimation release];
}
Answer on the basis of Mohit Gupta's pastie link:
Set CALayer on which you want image sequence animation
CALayer *animationLayer = [CALayer layer];
[animationLayer setFrame:CGRectMake(125, 0, 240, 300)];
[self.baseLayer addSublayer:animationLayer];
Define Array of Images needed to be shown in sequence animation
NSArray *animationFrames = [NSArray arrayWithObjects:(id)[UIImageimageNamed:#"1.png"].CGImage, (id)[UIImage imageNamed:#"2.png"].CGImage, (id)[UIImage imageNamed:#"3.png"].CGImage, nil];
Using CAKeyframeAnimation to display array of images in sequential manner
CAKeyframeAnimation *frameAnimation = [[CAKeyframeAnimation alloc] init];
[frameAnimation setKeyPath:#"contents"];
frameAnimation.calculationMode = kCAAnimationDiscrete; //mode of transformation of images
[animationLayer setContents:[animationFrames lastObject]]; //set the array objects as encounterd
frameAnimation.autoreverses = NO; //If set Yes, transition would be in fade in fade out manner
frameAnimation.duration = ((float)[animationFrames count])/4.5; //set image duration , it can be predefined float value
frameAnimation.repeatCount = HUGE_VAL; //this is for inifinite, can be set to any integer value as well
[frameAnimation setValues:animationFrames];
[frameAnimation setRemovedOnCompletion:YES];
[frameAnimation setDelegate:self];
[animationLayer addAnimation:frameAnimation forKey:#"contents"]; //add animation to your CALayer
[frameAnimation release];
Hope this helps

Coreplot Library - Extract entire graph image

i am creating image for graph using this code
UIImage *newImage=[graph imageOfLayer]
NSData *newPNG= UIImageJPEGRepresentation(newImage, 1.0);
NSString *filePath=[NSString stringWithFormat:#"%#/graph.jpg", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
if([newPNG writeToFile:filePath atomically:YES])
NSLog(#"Created new file successfully");
But i get only visible area(320*460) in image, How can i get whole graph image with axis.
Please provide some code snippet, how can i do it with coreplot.
Thanks In Advance...
Make a new graph the size of the desired output image. It doesn't have to be added to a hosting view—that's only needed for displaying it on screen.
CPTXYGraph *graph = [(CPTXYGraph *)[CPTXYGraph alloc] initWithFrame:desiredFrame];
// set up the graph as usual
UIImage *newImage=[graph imageOfLayer];
// process output image
My approach to this problem was to create a method to extract the image.
In that method I momentarily make the hosting view, scroll view, graph bounds, and plot area frame bounds momentarily bigger. I then convert the graph to a an image.
I then remove the hosting view from its container to remove it from screen. I then call the doPlot method to reinitialise the plot and its data via the DoPlot method. My code is below.
There might be a visual jitter whilst this is carried out. However, you could always disguise this by using a alert either to enter an email for export, or just a simple alert saying image exported.
//=============================================================================
/**
Gets the image of the chart to export via email.
*/
//=============================================================================
-(UIImage *) getImage
{
//Temprorarilty make plot bigger.
// CGRect rect = self.hostingView.bounds;
CGRect rect = self.scroller.bounds;
rect.size.height = rect.size.height -100;
rect.origin.x = 0;
rect.size.width = rect.size.width + [fields count] * 100.0;
[self.hostingView setBounds:rect];
[scroller setContentSize: hostingView.frame.size];
graph.plotAreaFrame.bounds = rect;
graph.bounds = rect;
UIImage * image =[graph imageOfLayer];//get image of plot.
//Redraw the plot back at its normal size;
[self.hostingView removeFromSuperview];
self.hostingView = nil;
[self doPlot];
return image;
}//============================================================================

Problem with uiimageView animation: animation stops

Here is my code:
-(void) createNewBall {
UIImage * image = [UIImage imageNamed:#"bulle_03.png"];
bulleBouge = [[UIImageView alloc] initWithImage:image];
[bulleBouge setCenter:[self randomPointSquare]];
[[self view] addSubview:bulleBouge];
}
-(void)moveTheBall{
bulleBouge.center = CGPointMake(imageView.center.x + X, imageView.center.y + Y);
}
createNewBall is called every two seconds. My problem is that every bulleBouge that is created stops moving after two seconds. I don't know why.
How can I solve this please?
It stops moving b/c u are initializing new bulleBouge every two seconds. You are also leakin memory since you never releasy it before assigning new value to it. so what happens is that after u create the imageView you only keep the reference to the lasts instance, hence only the last one is changing position. To fix this store all your new uiImageViews in an array and move them randomly after two seconds.
-(void) createNewBall {
UIImage * image = [UIImage imageNamed:#"bulle_03.png"];
UIImageView *bulleBouge = [[UIImageView alloc] initWithImage:image];
[bulleBouge setCenter:[self randomPointSquare]];
[bulleBougeArray addObject:bulleBouge];
[[self view] addSubview:bulleBouge];
[bulleBouge release];
}
-(void)moveTheBall{
for(int i=0; i< [bulleBougeArray count];i++){
UIImageView *bulleBouge = [bulleBougeArray objectAtIndex:i];
bulleBouge.center = CGPointMake(imageView.center.x + X, imageView.center.y + Y);
}
}
Cyprian is correct. In a simpler form, you're creating a new bulleBouge every two seconds, under the same variable. The program already has one, but since you told it to make a new one under the same ivar it forgets the old one, and thus doesn't move it. You need an array so that each ball can be remembered separately, and thus moved separately as seen in the example code that he posted.

Loading more than 10 images on iPhone?

I'm trying to add more than 10 pictures on ScrollView.
NSUInteger i;
for (i = 1; i <= numberOfImage; i++)
{
NSString *imageName = [NSString stringWithFormat:#"d%dimage%d.png", imageSection, i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollView addSubview:imageView];
[imageView release];
}
This code is from Apple example and it works fine. But if the variable 'i' is bigger than 10, 'UIImage *image' is empty. The imageName seems to correct. But I don't know why it does not load image. Does anybody sees the problem??
And one more thing. If I do like that, does iOS controls memory automatically? I mean it's kind of wasting memory if all (more than 10) images are loaded on memory even they are not displayed. I've heard that iOS loads images only displayed on screen and free images those are not displayed. Is that right?
Thanks for reading.
UIimage imageNamed: does cache file contents. I recommend you to use UIImage +imageWithContentsOfFile: that doesn't cache at all in such situation.
You have to make sure the images have the correct name (like 0dimage11.jpg) and are added to the XCode project.
You probably have to set the contentSize accordingly.
IOS will not do that magic memory management thing unless you are using a CATiledLayer based UIView.
If UIImage is not created, it because the name does not refer to an image in the resource folder and you should have an exception.
You need to have the correct file names. You said you think the file names are correct.
NSLog(#"Loop %d: d%dimage%d.png", i,imageSection, i]);
Log out the file names so you can see what the names actually are. Place that line in your loop.
NSUInteger i;
for (i = 1; i <= numberOfImage; i++)
{
NSString *imageName = [NSString stringWithFormat:#"d%dimage%d.png", imageSection, i];
NSLog(#"Loop %d: d%dimage%d.png", i,imageSection, i]);
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollView addSubview:imageView];
[imageView release];
}
Then monitor the filenames in the debugger and see if those image files exist, and in the same directory where Apple put their image files.
Hey,Its not good way to load 10 images at once.All things you have done correct and still you'r image display empty then please check log may be there is memory warning.You can you apple's sample code photoscroller. It will do all thing that you want and also manages good memory.there are two method one is using CATieldLayer and another one directly load images. I recommended you to use method that uses CATieldLayer.
Sorry guys. This is turned out to be my fault. well, not exactly MY fault. Designers throw me many files with wrong filenames like d1imgae11.png... Anyway tips from all you guys gave me different view to see the problem and I got another hint about not to cache images. Thanks.

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.