Problem with uiimageView animation: animation stops - iphone

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.

Related

Putting two backgrounds one after the other in objective-c iphone game?

Hi I am creating an iphone game
in my game layer, I have two identical background images but I want them to go one after the other.
Once the game animal (eg a penguin) crosses the first background, I want the first background to go after the second one-- becoming a continuous background until the game is over.
I have tried everything--- for loops, while loops and such but nothing seems to work
Does anyone have an idea for how I could go about doing this?
Thank you for any help you can provide me.
this is all I have so far after many different tries
- (id) init
{
if((self = [super init]))
{
for ( int x = 0; x < 10000000; ++x)
{
CCSprite *bg = [CCSprite spriteWithFile:#"level1.png"];
[bg setPosition:ccp(160,240)];
ccTexParams params = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT};
[bg.texture setTexParameters:&params];
[self addChild:bg z:0];
CCSprite *bg2 = [CCSprite spriteWithFile:#"level1.png"];
[bg2 setPosition:ccp(320,480)];
ccTexParams param = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT};
[bg2.texture setTexParameters:&param];
[self addChild:bg z:0];
}
If the backgrounds are the identical you don't actually need 2 images, you can just set the texture rect position of the one and it will continuously move. If you call moveBackground on a timer or in the update method it will continually scroll.
-(void)init
{
if((self=[super init]))
{
background = [CCSprite spriteWithFile:#"background.png"];
ccTexParams params = {GL_LINEAR,GL_LINEAR,GL_REPEAT,GL_REPEAT};
[background.texture setTexParameters:&params];
[self addChild:background z:0];
}
}
-(void)moveBackground
{
// Scroll background 5 pixels to the left
int speed = 5;
background.textureRect = CGRectMake(background.textureRect.origin.x-speed,
background.textureRect.origin.y,
background.textureRect.size.width,
background.textureRect.size.height);
}

UIImageView Leak / Autorelease

I am running a fairly memory intensive loop to generate images and have come unstuck in memory leaks / the autorelease retaining memory allocations for too long.
Can anyone please explain exactly what is being held and autoreleased below? I have run this through the Allocations instrument and it increases in size until the loop finishes and deallocates all of the autorelease objects (as I understand it from 3 days of trial and error). This is ok for less loops but when I exceed 200 it eventually crashes before it gets to autorelease. By commenting out the following code, this increase stops and the Instruments graph stays horizontal with a set amount of memory:
for (int l=0;1 < 300; 1++) {
UIImage * Img = [[UIImage alloc] initWithContentsOfFile:Path]; //Path is a NSString pointing to bundlePath and a sample image
UIImageView *ImgCont = [[UIImageView alloc] initWithImage:Img];
//here I usually add the view to a UIView but it is not required to see the problem
ImgCont.frame = CGRectMake(x, y, w, h);
[ImgCont release];
[Img release];
}
I have tried wrapping this with a NSAutoreleasePool without success - any ideas what I'm doing wrong?
Thanks,
When you add the imageView to a view, it's retained by that view, so even if you release Img and ImgCont, they still exist, and you are left with 300 objects.
Also, and I'm not completely sure about this, but if you are using the same image over and over, you should use [UIImage imageNamed:NAME], since it reuses the images, something I can not say for [UIImage initWithContentsOfFile:PATH]; (If the OS doesn't optimize that case, right now you have the same image 300 times in the memory).
None of the objects you are explicitly creating are being autoreleased so it must be stuff inside those UIKit calls you have. There's not a lot you can do about that though in terms of cutting down the number of autoreleases. But what you can do is mess around with autorelease pools.
You say you've tried NSAutoreleasePool but have you tried wrapping each iteration of the loop in a pool like so:
for (int l=0;1 < 300; 1++) {
#autoreleasepool {
UIImage * Img = [[UIImage alloc] initWithContentsOfFile:Path]; //Path is a NSString pointing to bundlePath and a sample image
UIImageView *ImgCont = [[UIImageView alloc] initWithImage:Img];
//here I usually add the view to a UIView but it is not required to see the problem
ImgCont.frame = CGRectMake(x, y, w, h);
[ImgCont release];
[Img release];
}
}
Although you should think about not doing it exactly like that, because it's possibly overkill. But I suggest you try that and if you're still having problems, then it's not this loop.

Better way to initialize UIImageView with non-zero origin

Creating UIImageView with some offset is quite common task when you're building interface in code.
I can see two ways to initialize UIImageView with origin not equal to (0,0):
First way requires only image filename and origin, but contains a lot of code (we can reduce number of lines by one using frame.origin = CGPointMake(x,y); ):
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image_filename"]];
CGRect frame = imgView.frame;
frame.origin.x = 150;
frame.origin.y = 100;
undoBg.frame = frame;
Second way has much less code, looks cleaner but we need to hardcode image size:
UIImageView *shadowView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 150, 800, 600)];
shadowView.image = [UIImage imageNamed:#"image_filename"];
What is best practice for you and why?
Thanks.
Hardcoding the images sizes is a form of Unnamed numerical constants which is an indication of Code Smell
This sort of thing should be avoided as much as possible as it can generate code that is a lot harder to maintain and is prone to human introduced errors. For example what happens when your graphic artist changes the size of the image? Instead of changing just one thing (the image) you now have to change many things (the image, and every place in the code where the image size has been hard coded)
Remember that you code not for today, but for the people who will come after you and maintain your code.
If anything, if you were really concerned about the extra lines of code, then you would abstract loading the UIImageView into a category, so that it can be used everywhere (note that this code is not tested):
#interface UIImageView (MyExtension)
-(UIImageView*)myLoadImage:(NSString*)named at:(CGPoint)location;
#end
#implementation
-(UIImageView*)myLoadImage:(NSString*)named at:(CGPoint)location
{
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:named]];
CGRect frame = imgView.frame;
frame.origin.x = location.x;
frame.origin.y = location.y;
return imgView;
}
#end
Then you could simply do:
UIImageView* imageView = [UIImageView myLoadImage:#"image_filename" at:CGPointMake(150,100)];
I use the second one with slight modification,
UIImageView *shadowView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 150, 800, 600)];
shadowView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:extension] ];
because imageNamed: caches image and cause memory leak.
I usually want my code to be easily readable. On the other hand I want the job done as fast as possible. In this case, there is so little code, I would go with less code. This is because I can get understand it so fast anyways. If it would be a much bigger example, I would use the easily readable code.
Surely it depends on your requirements. If I need to create an imageView in a class where the offset may change then I might do something like:
int myX = 10;
int myY = 100;
int myWidth = 200;
int myHeight = 300;
UIImageView *shadowView = [[UIImageView alloc] initWithFrame:CGRectMake(myX, myY, myWidth, myHeight)];
shadowView.image = [UIImage imageNamed:#"image_filename"];
but if I don't need to vary the offset and I know for a fact that the value won't change and no-one else will be needing to read or re-use my code then there's maybe nothing wrong (imho) with just using numbers in place of the int vars.
btw, you might want to avoid imageNamed as it caches the image which can lead to leaks.

Please help! Creating new objects (from array?) after an object completes task

I am writing an iPhone application and here is the overall synopsis:
An object is on the screen and moves based on accelerometer input - I have that working - it moves to the edge of the screen and doesn't go off = perfect. Now, what I want to happen is as soon as that object hits any of the four screen edges, it should stop and stay put on the screen, and a new object should 'appear' and start moving due to the accelerometer input, so now two objects would be on the screen, but only 1 moving. Eventually there could be 20 objects built up around the edge, but only 1 object will be moving at a time.
So I have now gotten the help I needed to check for edge hits etc, but I am now trying to switch the way I was getting boxes to show up on the screen. I originally was putting images on the screen through the view controller, but now what I want to do is start with one box in the center, when it hits an edge, it should stop and stay, and a new image will appear in the center and start moving due to accel input as described above. So do I just use an array to pull the images from? Do I not even put .png's on the view controller and should I just code it? Here is some of what I have trying to do this through an array:
//In my .h
UIImageView *blocks;
NSString *blockTypes[3];
//In my .m
blockTypes[0] = #"greenBox1.png";
blockTypes[1] = #"greenBox2.png";
blockTypes[2] = #"greenBox3.png";
Thanks in advance for any help! The help so far has been great!
You should't test if newX and newY are equal to 30 and 50. You should test if they are less than 30 and 50 respectively.
Edit:
I would do it like this:
loat newX = [mutableBoxArray lastObject].center.x + (accel.x * 12);
float newY = [mutableBoxArray lastObject].center.y + (accel.y * -12);
if(newX > 30 && newY > 50 && newX < 290 && newY < 430) {
[[mutableBoxArray lastObject] setCenter: CGPointMake(newX, newY)];
} else {
MyBox *myBox = [[MyBox alloc] init];
[mutableBoxArray addObject: myBox];
[myBox release];
}
Edit 2:
Add the following in your interface file
NSMutableArray *mutableBoxArray;
NSArray *imageNamesArray;
Then in your implementation file in the loadView add
mutableBoxArray = [[NSMutableArray alloc] init];
imageNamesArray = [[NSArray alloc] initWithObjects: #"orangeBox1.png",
#"blueBox1.png", #"greenBox1.png", #"pinkBox1.png", nil];
Then change the above method to
static NSInteger imageInt = 0;
loat newX = [mutableBoxArray lastObject].center.x + (accel.x * 12);
float newY = [mutableBoxArray lastObject].center.y + (accel.y * -12);
if(newX > 30 && newY > 50 && newX < 290 && newY < 430) {
[[mutableBoxArray lastObject] setCenter: CGPointMake(newX, newY)];
} else {
if (imageInt < [imageNamesArray count]) {
UIImage *image = [UIImage imageNamed: [imageNamesArray objectAtIndex: imageInt++]];
UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
[imageView setCenter: CGPointMake(100.0f, 100.0f)];
[mutableBoxArray addObject: imageView];
[imageView release];
}
}

Preloading a UIImageView animation using objective c for the 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,