IOS UIImageView in cell has wrong size - ios

I'm trying to replace an Image from an URL if it exists.
The problem seems to be that I can't set the size of my UIImageView.
My Code looks like this:
UIImageView *partnerIcon = (UIImageView*)[cell viewWithTag:0];
NSURL *imageUrl = [NSURL URLWithString:[[#"http://www.fitpas.ch/coreapp/resources/images/center/" stringByAppendingString:[[result objectAtIndex:indexPath.row] objectForKey:#"cid"]] stringByAppendingString:#".jpg"]];
UIImage* partnerImage = [UIImage imageWithData: [NSData dataWithContentsOfURL: imageUrl]];
if (partnerImage != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
//change image
partnerIcon.image = partnerImage;
partnerIcon.contentMode = UIViewContentModeScaleToFill;
});
}
This results in:
In the Image above the last row partnerImage is nil and that shows how it should be.
I tried to scale the UIImage with
partnerIcon.image = [UIImage imageWithCGImage:partnerImage.CGImage
scale:1/100 orientation:partnerImage.imageOrientation];
but this won't change anything.
I also tried to set to change the dimension of the UIImageView with:
partnerIcon.bounds = CGRectMake(0, 0, 50, 50);
and also
partnerIcon.frame = CGRectMake(0, 0, 50, 50);
but this isn't working either.

Set an explicit width and height constraint on the image view. If you don't do this then the content hugging and compression values will be used across all of the views to decide how big each should be based on the content size.

Related

Loading Remote images in TableView while keeping sizes intact

I want to show a table view where each cell will just contain one image. Images are loaded from respective URLs and there is no restriction on the size of the image.
I want to show the image in each cell with their proper sizes - that is maintain the aspect ratio. I am guessing this would entail having dynamic heights for each cell. But I am not sure and can't find a resource which explains how to achieve this.
What would be the best way to do this?
You need to get the image height and width dynamically first and set the same hieght and width to your table view cells.
I have not added table view but just some code will help you see how you can show two different images with their original height and width and adding the same to a view.
NSURL *imageURL1 = [NSURL URLWithString:#"http://cdn.macrumors.com/article-new/2014/12/applelogo.png"];
NSData *imageData1 = [NSData dataWithContentsOfURL:imageURL1];
UIImage *image1 = [UIImage imageWithData:imageData1];
UIImageView *imageView1 = [[UIImageView alloc] initWithImage: image1];
//CGFloat height = imageView.frame.size.height;
//CGFloat width = imageView.frame.size.width;
[self.view addSubview:imageView1];
//sample urls :- http://pre01.deviantart.net/e711/th/pre/f/2013/179/2/c/ios_7_icons__updated__by_iynque-d69mme1.png
NSURL *imageURL2 = [NSURL URLWithString:#"http://icons.iconarchive.com/icons/position-relative/social-2/128/ios-icon.png"];
NSData *imageData2 = [NSData dataWithContentsOfURL:imageURL2];
UIImage *image2 = [UIImage imageWithData:imageData2];
UIImageView *imageView2 = [[UIImageView alloc] initWithImage: image2];
CGFloat height = imageView2.frame.size.height;
CGFloat width = imageView2.frame.size.width;
imageView2.frame = CGRectMake(0, 300, width, height);
NSLog(#"height :- %f, Width :- %f ",height, width);
[self.view addSubview:imageView2];
Hopefully, you are loading the images asynchronously, as answered here: Loading images for UITableViewCell from URL (need to load them asynchronously)
You'll need a custom cell or prototype cell with a UIImageView set to UIViewContentModeScaleAspectFit. In the cell, set the constraints how you want them: that is, if you want the image to be the full width of the screen, set leading and trailing constraints, and constrain to the top and bottom.
Then, set your table view to use dynamic sizing:
tableView.estimatedRowHeight = 80.0; //or some reasonable first approximation
tableView.rowHeight = UITableViewAutomaticDimension;

UIImageView has weird space to the left of the image in a tableview

I have a UITableView that I programatically add to my view. I then load the data from an API, and resize the images to fit it to the width of the current device, and accordingly adjust the height of the image to keep the aspect ration, I then use that height as the height of the cells for my table view.
Here is some code and a screenshot of the result:
This is the image resize code:
+ (UIImage*)imageWithImage:(UIImage *)image convertToWidth:(float)width {
float ratio = image.size.width / width;
float height = image.size.height / ratio;
CGSize size = CGSizeMake(width, height);
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage * newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimage;
}
This is in the init method of my custom table view cell:
_imgPicture = [[UIImageView alloc] init];
_imgPicture.contentMode = UIViewContentModeScaleAspectFit;
[self.contentView addSubview:_imgPicture];
This is my cellForRowAtIndexPath
RecipeTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:#"recipe_cell"];
if(cell == nil)
{
cell = [[RecipeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"recipe_cell"];
}
NSDictionary *dict = [recipeArray objectAtIndex:[indexPath row]];
cell.lblName.text = [dict valueForKey:#"name"];
if([#"data:image/jpg;base64,null" isEqualToString:[NSString stringWithFormat:#"%#,%#",[dict valueForKey:#"pictureType"], [dict valueForKey:#"picture"]]])
{
cell.imgPicture.image = defaultImage;
}
else
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#,%#",[dict valueForKey:#"pictureType"], [dict valueForKey:#"picture"]]];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *ret = [UIImage imageWithData:imageData];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
cell.imageView.image = [ImageExtension imageWithImage:ret convertToWidth:screenWidth];
}
return cell;
I have tried forcing the UIImageView to be at origin 0, 0 by settings the frame, but that didn't help, I am now thinking that it might be the fact that the image gets resized, and then something in the UITableViewCell breaks, but have no idea what it could be. Some assistance with this will be much appreciated.
Also note I had all this as a storyboard, and it had the exact same result, then I thought let me attempt it programatically and getting the same results.
Change
cell.imageView.image
^^^^^^^^^
to
cell.imgPicture.image
^^^^^^^^^^
This will solve problem...
first u can ensure resizing of image by giving tableview any backgroundcolor
secondly, if using ios8 then see your constraits
thirdly, if any ios then check indentation of uitableviewcell

iOS - Cell image blurred

I have placed an image in a UITableViewCell and for some reason, the image is a bit blurred...
This is what I'm using:
NSURL *urlForProfileImage = [NSURL URLWithString: [_currentTweet[#"user"] objectForKey:#"profile_image_url_https"]];
UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:urlForProfileImage]];
cell.imageView.image = thumbnail;
Is there another way to provide the desired result but maintain the images quality?
Reason :
The default imageView size is 40x40 and so your image needs to be 80x80 pixels (retina display).
But the image that you are getting from the "pbs.twimg.com/profile_images/192098593/Apple_normal.png" is 48x48.
And so it is blurred.
Solution :
One option is that you add a custom imageView which is 24x24. (width : 24 & height : 24) Then your image will not show blurred.
Or, you can try modifying the height and width of the imageView by subclassing the class UITableViewCell and using its layoutSubviews method. The "trick" is to write layout code in this method, otherwise the code does not have any effect :
- (void)layoutSubviews {
[super layoutSubviews];
self.imageView.bounds = CGRectMake(0,0,24,24);
self.imageView.frame = CGRectMake(0,0,24,24);
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
CGRect tmpFrame = self.textLabel.frame;
tmpFrame.origin.x = 30;
self.textLabel.frame = tmpFrame;
tmpFrame = self.detailTextLabel.frame;
tmpFrame.origin.x = 30;
self.detailTextLabel.frame = tmpFrame;
}

How to get rid of massive Memory leak with blurred image in uitableview cell

Somehow when I scroll to the bottom of my table (96 items only) I get 1 gb of memory usage (it increase for every cell that gets created. I have a table that has an image with a blurred image in front of it that is using a cropped version of the original image with text then on top of that. Pretty simple. I'm using the apple provided sample code for blurring images available here: https://github.com/iGriever/TWSReleaseNotesView/blob/master/TWSReleaseNotesView/UIImage%2BImageEffects.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"itemCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *foodItem = [self.foodItems objectAtIndex:indexPath.row];
// Set up the image view
UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
UIImage *foodImage = [UIImage imageNamed:[foodItem objectForKey:FOOD_IMAGE_FILE_KEY]];
[imageView setImage:foodImage];
[imageView setContentMode:UIViewContentModeScaleAspectFill];
// Set up the label
UILabel *labelView = (UILabel *)[cell viewWithTag:2];
[labelView setFont:[UIFont flatFontOfSize:20.0]];
labelView.text = #"Blah";
// Set up the image view
UIImageView *blurredView = (UIImageView *)[cell viewWithTag:3];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *blurredImage = [[self cropForBlur:foodImage] applyBlurWithRadius:4
tintColor:[UIColor colorWithWhite:1.0 alpha:0.2]
saturationDeltaFactor:1.2
maskImage:nil];
dispatch_sync(dispatch_get_main_queue(), ^{
blurredView.image = blurredImage;
});
});
return cell;
}
*Note: I know it is most likely the blur (as opposed to my cropping) as it only happens when I do the blur. Also it's nothing to do with the async dispatch stuff as it still happens if I don't do that.
Yes I'm using ARC. Yes I'm using storyboards.
Here's cropForBlur:
- (UIImage *)cropForBlur:(UIImage *)originalImage
{
CGSize size = [originalImage size];
int startCroppingPosition = 100;
if (size.height > size.width) {
startCroppingPosition = size.height/2 + ((size.width / 320) * 45);
} else {
startCroppingPosition = size.height/2 + ((size.width / 320) * 45);
}
// WTF: Don't forget that the CGImageCreateWithImageInRect believes that
// the image is 180 rotated, so x and y are inverted, same for height and width.
CGRect cropRect = CGRectMake(0, startCroppingPosition, size.width, ((size.width/320) * 35));
CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:(size.width/160) orientation:originalImage.imageOrientation];
CGImageRelease(imageRef);
return newImage;
}
I've also tried looking in Instruments but it will show that I'm using heaps of memory in total but the big chunks of memory don't show up in the breakdown. Weird.
Here's the bit that's saying I am using heaps of memory in the left bar.
Here's the allocations bit in Instruments. I don't see how they could match up. I haven't got zombies on or anything (unless there's somewhere other that in edit scheme to change that).
Here's the leaks Instruments view after scrolling down a bit. Doesn't seem to show any real leaks :S So confused.
See the solution from this link. The problem is the image has a different scale from your screen scale. The final output image can be very big.

Can you display a small image in a detailTextLabel cell?

So I was wondering if it is possible to display a small image in a detailTextLabel of a cell? (I'm getting the image from a URL) I tried it with:
NSString *thumbs = [NSString stringWithFormat:#"%#", TableText3];
cell.detailTextLabel.text = thumbs;
Which for obvious reason doesn't work. I also tried with:
UIImage *thumbs = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:TableText3]]];
cell.detailTextLabel.text = thumbs;
Which also (obviously) doesn't work, because I'm passing an image to a string parameter.
Surprisingly I didn't find anything on the WWW. (Search parameters were: "image in detailTextLabel" or picture or just textlabel and image and various variations)
You can't put it directly into the label because labels only display text. But you can use the imageView property of the UITableViewCell.
cell.imageView = [[UIImageView alloc] initWithImage: thumbs];
https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html
Rather than putting the image in the imageView property, you could create an UIImageView and place it in the accessoryView property:
UIImage * thumbs;
UIImageView * thumbsView;
CGFloat width;
thumbs = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:TableText3]]];
thumbsView = [[[UIImageView alloc] initWithImage:thumbs] autorelease];
width = (cell.frame.size.height * thumbs.size.width) / thumbs.size.height;
thumbsView.frame = CGRectMake(0, 0, width, cell.frame.size.height);
cell.accessoryView = thumbsView;
This will size the image to fit within the cell and position it to the right of the textLabel and detailTextLabel.
A better approach is not to rely on the built-in UITableViewCell types and create your own cell frame and add all the labels, view, images at your desired position inside the cell. Then you can return the cell for your tableview.

Resources