UIImageView.image bigger than UIImageView - objective-c

I have a UIImageView in a custom tableview cell. When I set the UIimageview property, the uiimageview.image is bigger than the uiimageview. Why?
Here is the code:
cell.imageView.image=[UIImage imageNamed:#"BlueMooseLogo.png"];
And here is a link to what the cell looks like. The blue square is the background of the imageview, and the blue moose is the image.
https://docs.google.com/document/d/1G7BYCriYbSGYHryP5OI7XHuVpqRKiNcBrxdY14wDgoA/edit?usp=sharing
If it's relevant, within interface builder, after I select the uiimageview, I have the view set to scale to fill.

I've faced the same problem, and tried a lot ways to fix it, finally, I did it. When you try to assign the image to your UIImageView, please resize your image as a thumbnail image, and use this thumbnail image to display. The following code just for your reference.
static func resizeImage(image:UIImage, toTheSize size:CGSize) -> UIImage{
let scale = CGFloat(max(size.width/image.size.width,
size.height/image.size.height))
let width:CGFloat = image.size.width * scale
let height:CGFloat = image.size.height * scale;
let rr:CGRect = CGRectMake( 0, 0, width, height);
UIGraphicsBeginImageContextWithOptions(size, false, 0);
image.drawInRect(rr)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return newImage
}

You most likely want the content mode to be "Aspect Fit" not "Aspect Fill".
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;

I think that it would be a clip subviews issue.
Check your UIImageView property.
Storyboard : check clip subviews in Attributes inspector
Code : imgView.clipsToBounds = YES

Related

Make image smaller inside UIImageView

I have an UIImageView that shows and image of a creditCard, My problem is that I want to make boarders around it, so the credit card wont touch the edges of the UIimageView, I dont want to change the UIImageView position on the screen so what can I do ?
image 1
image 2
( unlike the example of the blue card it dosnt have to leave spaces only from the sides, it could shrink it from all sides )
You basically have (3) three options that can fix this.
Adjust the UIViewContentMode contentMode of the UIImageView so that it appropriately displays the image (this will only work however if the image you are using scales to fit without touching the border.
Use a UIButton instead and simply adjust the image insets until your satisfied (just disable the button or set user interaction to no here to "mimic" an image view)
Create a wrapper method that creates a new image to your desired size. Something like this should work just fine
CGSize size = CGSizeMake(< some width > , < some height >);
Then just create a new image capture with the size you've chosen
CGFloat scale = MAX(size.width/image.size.width, size.height/image.size.height);
CGFloat width = image.size.width * scale;
CGFloat height = image.size.height * scale;
CGRect imageRect = CGRectMake((size.width - width)/2.0f,
(size.height - height)/2.0f,
width,
height);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
[image drawInRect:imageRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
From here you should then be able to just apply a border width and color to get your desired result!
I guess a fourth (4th) option could be manually shrinking the image (with some photo editor) so that it renders (fits) into your image view with the appropriate padding around the image. I think the others are easier and best practice though.

Using cornerRadius on a UIImageView in a UITableViewCell

I'm using a UIImageView for each of my UITableViewCells, as thumbnails. My code uses SDWebImage to asynchronously grab those images from my backend and load them in, and then caching them. This is working fine.
My UIImageView is a 50x50 square, created in Interface Builder. Its background is opaque, white color (same as my UITableViewCell background color, for performance). However, I'd like to use smooth corners for better aesthetics. If I do this:
UIImageView *itemImageView = (UIImageView *)[cell viewWithTag:100];
itemImageView.layer.cornerRadius = 2.5f;
itemImageView.layer.masksToBounds = NO;
itemImageView.clipsToBounds = YES;
My tableview drops around 5-6 frames immediately, capping about 56 FPS during fast scrolling (which is okay), but when I drag and pull the refresh control, it lags a bit and drops to around 40 FPS. If I remove the cornerRadius line, all is fine and no lag. This has been tested on an iPod touch 5G using Instruments.
Is there any other way I could have a rounded UIImageView for my cells and not suffer a performance hit? I'd already optimized my cellForRowAtIndexPath and I get 56-59 FPS while fast scrolling with no cornerRadius.
Yes, that's because cornerRadius and clipToBounds requires offscreen rendering, I suggest you to read these answer from one of my question. I also quote two WWDC session thatyou should see. The best thing you can do is grab the image right after is downloaded and on another thread dispatch a method that round the images. Is preferable that you work on the image instead of the imageview.
// Get your image somehow
UIImage *image = [UIImage imageNamed:#"image.jpg"];
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
cornerRadius:10.0] addClip];
// Draw your image
[image drawInRect:imageView.bounds];
// Get the image, here setting the UIImageView image
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
Method grabbed here
You can also subclass the tableviewcell and override the drawRect method.
The dirty but very effective way is draw a mask in photoshop with inside alpha and around the matching color of the background of the cell and add another imageView, not opaque with clear background color, on the one with images.
There is another good solution for this. I did it a few times in my projects. If you want to create a rounded corners or something else you could just use a cover image in front of your main image.
For example, you want to make rounded corners. In this case you need a square image layer with a cut out circle in the center.
By using this method you will get 60fps on scrolling inside UITableView or UICollectionView. Because this method not required offscreen rendering for customizing UIImageView's (like avatars and etc.).
Non blocking solution
As a follow up to Andrea's response, here is a function that will run his code in the background.
+ (void)roundedImage:(UIImage *)image
completion:(void (^)(UIImage *image))completion {
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
CGRect rect = CGRectMake(0, 0, image.size.width,image.size.height);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:rect
cornerRadius:image.size.width/2] addClip];
// Draw your image
[image drawInRect:rect];
// Get the image, here setting the UIImageView image
UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
dispatch_async( dispatch_get_main_queue(), ^{
if (completion) {
completion(roundedImage);
}
});
});
}
Swift 3 version of thedeveloper3124's answer
func roundedImage(image: UIImage, completion: #escaping ((UIImage?)->(Void))) {
DispatchQueue.global().async {
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
// Add a clip before drawing anything, in the shape of an rounded rect
UIBezierPath(roundedRect: rect, cornerRadius: image.size.width/2).addClip()
// Draw your image
image.draw(in: rect)
// Get the image, here setting the UIImageView image
guard let roundedImage = UIGraphicsGetImageFromCurrentImageContext() else {
print("UIGraphicsGetImageFromCurrentImageContext failed")
completion(nil)
return
}
// Lets forget about that we were drawing
UIGraphicsEndImageContext()
DispatchQueue.main.async {
completion(roundedImage)
}
}
}

iPad UIImageView creates aliased edges when scaling down larger UIImages, but not when displaying a screenshot of itself.

I'm running into a weird issue with a UIImage displayed within a UIImageView.
If I put a 1024x1024 image within a 173x173 image view with "scale to fill" set, the result is aliased. However, if I put the same image in, then take a screenshot of the imageview and assign it back, the image is displayed perfectly. This bothers me, because the screenshot is supposed to be the exact pixels that I'm seeing within the image view.
On the left is the result of assigning an image directly. On the right is taking a screenshot of the same image and assigning it back. Notice how the Es are jagged on the left, but smooth on the right.
Is this an issue with the content mode of the image view or something that happends during the sreenshot?
for(UIImageView* placeholderView in self.placeholderImageViews)
{
//assigning a 1024x1024 image into a smaller image view results in an aliased image here
placeholderView.image = imageToDisplay;
//this code makes the image appear perfectly scaled down
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
{
UIGraphicsBeginImageContextWithOptions(placeholderView.frame.size, NO, [UIScreen mainScreen].scale);
}
else
{
UIGraphicsBeginImageContext(placeholderView.frame.size);
}
[placeholderView.layer renderInContext:UIGraphicsGetCurrentContext()];
screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//save the result
placeholderView.image = screenshot;
}
UIImageView scaling sucks; you should always give it an image with exactly the same size of its bounds, so it does not have to scale it down.
Check this code and the example.
Swift extension:
extension UIImage{
// returns a scaled version of the image
func imageScaledToSize(size : CGSize, isOpaque : Bool) -> UIImage{
// begin a context of the desired size
UIGraphicsBeginImageContextWithOptions(size, isOpaque, 0.0)
// draw image in the rect with zero origin and size of the context
let imageRect = CGRect(origin: CGPointZero, size: size)
self.drawInRect(imageRect)
// get the scaled image, close the context and return the image
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
Example:
aUIImageView.image = aUIImage.imageScaledToSize(aUIImageView.bounds.size, isOpaque : false)
Set isOpaque to true if the image has no alpha: drawing will have better performance.

UIScrollView won't adjust height to fit subviews

I have a UITextView, which sets its text dynamically from an RSS feed. The textview is a subview of a UIScrollview. Ultimately, I am creating a mobile newspaper app, so the user should be able to scroll through the text (and other subviews).
After creating the views in IB, I added
NSString *sourceCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:self.URL] encoding:NSUTF8StringEncoding error:&error];
sourceCode = [self parseHTMLText:sourceCode];
CGSize maximumLabelSize = CGSizeMake(320,9999);
CGSize txtStringSize = [sourceCode sizeWithFont:self.body.font
constrainedToSize:maximumLabelSize];
CGRect newlblFrame = CGRectMake(0, 0, 320, txtStringSize.height);
self.body.frame = newlblFrame; //body is the textview
self.body.text = sourceCode;
self.scroll.contentSize=CGSizeMake(320, self.body.frame.size.height+300); //scroll is scrollview
A typical NSLog will display body frame = {{0, 0}, {320, 2088}} scrollview frame = {{0, 0}, {320, 417}} scrollview content size = {320, 2388}
However, when I run the app, body maintains its interface builder height of around 196 and the scrollview won't scroll (when i move it, it just bounces back to its original position)
On a side note, when I try to manually change the frame of the textview with CGRectMake, the NSLog shows the correct height, but the view doesn't appear different. I made sure that it's hooked up correctly in IB, because I can adjust other properties, like background color.
EDIT:
After I set the cliptoBounds property of the textview to NO, the textview now adjusts its height and tries to show the entire text. However, it cuts off at the end of the screen, and I still cannot scroll.
Here is what I see currently. I made the scrollview background color gray for convenience. I'm not sure why part of the scrollview is partially in white and and partially gray. (Title) is a separate label btw)
I fixed the problem by moving the code from viewDidLoad to viewDidAppear. Apparently this is an Xcode 4.5 specific issue, resulting from the AutoLayout feature overriding the logic in the viewDidLoad method. A better explanation can be found here.
i hope this will help you
self.scrollview.contentSize=CGSizeMake(320, label.frame.size.height+30);
Try to add this :
[_scrollView setClipsToBounds:YES];
Try this:
CGSize maximumSize = CGSizeMake(200.0, 30.0); // Specify your size. It was for my screen.
UIFont *txtFont = <Ur Font size & Var>;
//new
//fontValue = txtFont;
//new
lblValue.font = txtFont;
lblValue.lineBreakMode = UILineBreakModeWordWrap;
CGSize txtStringSize = [commentTxt sizeWithFont:txtFont
constrainedToSize:maximumSize
lineBreakMode:lblValue.lineBreakMode];
CGRect newlblFrame = CGRectMake(105.0, y, 200.0, txtStringSize.height);
lblValue.frame = newlblFrame;
lblValue.text = #"Your String";
After this set scroll Content size. Hope it'll work for you. It worked for me.
Try to solve in the following way.
// adjust the height of UITextView with content height
CGRect frame = self.body.frame;
frame.size.height = self.body.contentSize.height;
self.body.frame = frame;
// adjust UIScrollView's height with the height of UITextView
self.scroll.frame = frame;

Is there a way to auto-size a UIImageView in Interface Builder/storyboard?

When you set a image for a uiimageview in storyboard or interface builder, it retains the shape of the original UIImageView, which means that the image itself is completely distorted.
To match the size of the UIImageView to its image, I have to manually enter in the size from the file inspector.
Is there a way that UIImageView can automatically detect the native size of its image and size its self accordingly?
I am assuming you are referring to layout in storyboard/IB. To get the native size of the image just select the image and press Command + = on the keyboard. the to re-size it proportionally select the corner and hold down the shift key when you re-size it.
Why don't you set the size of your uiimageview in code?
Here's what you need to do...
//get the Image
UIImage *img = [UIImage imageNamed:#"img.png"];
CGFloat x = img.origin.x;
CGFloat y = img.origin.y;
CGFloat width = img.size.width;
CGFloat height = img.size.height;
imageView.frame = CGRectMake(x, y, width, height); //imageView is your uiimageview's reference
Use the contentMode
 imageView.contentMode = UIViewContentModeScaleAspectFit;
Edit :
I just saw you seem to want to adjust imageViews size to the image.... Different then
This is what I did:
imageView.clipsToBounds = YES;
[imageView setContentMode: UIViewContentModeScaleAspectFit];
That is working for me.