Reputation: 2352
I'm trying to calculate the appropriate height for a UITableViewCell and a UIImageView by using the following method that gets called:
-(void)ratioCalculator
{
picH = image.size.height;
picW = image.size.width;
NSLog(@"%d = width %d = height", picW, picH);
picRatio = (picW/picH);
NSLog(@"%F", picRatio);
imageViewH = (260/picRatio);
NSLog(@"%d int", imageViewH);
return;
}
The thing is, when it gets called, the picRatio = (picW/picH);
doesn't seem to be happening as the console says this:
2012-11-18 21:56:48.787 Name[5374:c07] 640 = width 360 = height
2012-11-18 21:56:48.788 Name[5374:c07] 1.000000
2012-11-18 21:56:48.788 Name[5374:c07] 260 int
The 1.000000 is the float picRatio
and the 260 is the imageViewH
. Obviously this means the incorrect heights are used for both the UITableViewCell and the UIImageView which are calculated like this:
else {
[self ratioCalculator];
return (imageViewH + 20);
}
and
- (void)showImage:(UIImage *)theImage
{
self.imageView.image = theImage;
self.imageView.hidden = NO;
[self ratioCalculator];
self.imageView.frame = CGRectMake(10, 10, 260, imageViewH);
self.photoLabel.hidden = YES;
}
As stupid a question as this probably is, why isn't this simple division working? Again, sorry if this is a stupid question, but it has me stumped. I feel like I'm going slightly mad.
Any help would be greatly appreciated,
Regards,
Mike
Upvotes: 1
Views: 104
Reputation: 36082
What you are missing is to cast the integers to float in order to make a float division
picRatio = (picW/picH); // gives an int division if picW and picH are declared integers
picRatio = (float)(picW)/picH; // gives you a floating point division
Upvotes: 2
Reputation: 2352
Since no one is posting an official answer, I thought I'd do so to help anyone in a similar position. The comments on my question put me on the right track, and after further investigations I discovered that the compiler calculates the output based on the types of the operands. Therefore, if all the operands are ints, it casts an int to the destination, regardless of if it's a float or not. Solution: make at least one of your operands a float.
Hope this helps anyone in a similar position.
Upvotes: 0
Reputation: 14667
picRatio = ((float)picW/(float)picH);
Objective-c needs the proper iVar type assignment before dividing. When you divide 2 integers, the output isn't a float, but an integer.
So 640/360 = 1.777 and this is treated as an integer, so the decimal value is ignores, which gives you the 1, you are getting.
If you do what I wrote, will actually produce a float, and give you the 1.777 output.
Upvotes: 3