Better way to initialize UIImageView with non-zero origin - iphone

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.

Related

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.

CALayer vs. drawInRect: performance?

I'm trying to draw some shadows in a rect. The shadow image itself is about 1px * 26px.
Here's two methods I've thought of for drawing the image in the view:
//These methods are called in drawRect:
/* Method 1 */
[self.upperShadow drawInRect:rectHigh]; //upperShadow is UIImage
[self.lowerShadow drawInRect:rectLow];
/* Method 2 */
CALayer *shadowTop = [CALayer layer];
shadowTop.frame = rectHigh;
shadowTop.contents = (__bridge id)topShadow; //topShadow is CGImage
[self.layer addSublayer:shadowTop];
CALayer *shadowLow = [CALayer layer];
shadowLow.frame = rectLow;
shadowLow.contents = (__bridge id)lowShadow;
[self.layer addSublayer:shadowLow];
/* Method 3 */
UIImageView *tShadow = [[UIImageView alloc] initWithFrame:rectHigh];
UIImageView *bShadow = [[UIImageView alloc] initWithFrame:rectLow];
tShadow.image = self.upperShadow;
bShadow.image = self.lowerShadow;
tShadow.contentMode = UIViewContentModeScaleToFill;
bShadow.contentMode = UIViewContentModeScaleToFill;
[self addSubview:tShadow];
[self addSubview:bShadow];
I'm curious which of these is better, when it comes to performance in drawing and animation. From my benchmarking it seems that the layers are faster to draw. Here are some benchmarking stats:
drawInRect: took 0.00054 secs
CALayers took 0.00006 secs
UIImageView took 0.00017 secs
The view which contains these shadows is going to have a view above it which will be animated (the view itself is not). Anything that would degrade the animation performance should be avoided. Any thoughts between the three methods?
If the shadows are static, then the best way is to use two UIImageViews. It's even smarter than CALayer about how to deal with static images (though I don't know if that's going to make a difference here), and will otherwise have the same benefits as CALayer, such as having all compositing being done on the GPU instead of on the CPU (as your Method 2 will require).

Creating a timer and using a bar to represent remaining time

I am currently in the process of creating a timer for a game but am getting a little confused about the best way to represent remaining time in the form of a bar. I have my timer up and running, and I was going to use this to scale an image to represent remaining time:
Time Passed / Total Time = Percentage Time Elapsed (x100 would be PTE but it's easier without)
Image Width = (1 - PTE) * StartImageWidth
I can't find any easy way of scaling an image in this format as the width param seems to be read only, and if I'm not mistaken the scaling functions are 4.x and later? So does anyone know the best way to do this?
Thanks,
Elliott
Try converting your bar image to a stretchableImage. I do something similar to this, but updating the time of day. Here's my code:
UIImage *dayPassed = [UIImage imageNamed:#"dayPassedSmall.png"];
UIImage *passed = [dayPassed stretchableImageWithLeftCapWidth:20.0 topCapHeight:0.0];
UIImageView *dayPassedView = [[[UIImageView alloc] initWithFrame:dayFrame] autorelease];
dayPassedView.image = passed;
[self.view addSubview:dayPassedView];
Then you can adjust the width later using:
CGRect imageFrame = dayPassedView.frame;
double relWidth = (1-PTE)*width;
imageFrame.size.width = relWidth;
dayPassedView.frame = imageFrame;
if you want to animate the change from the old frame to the new one, you can, but I think the main thing is the image has to be stretchable.
Try this
[UIView animateWithDuration:0.1 animations: ^ {
CGRect frame = CGRectMake(xMargin, yMargin, width, height);
myBar.frame = frame;
}];

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,

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.