How to manage UIImageView content mode? - iphone

I have an UIImageView with some fixed rect size. But my images are not fixed in size. I want to display images according to UIImageView's rect size. Whether image is big or large in resolution it must be in fixed display according to UIImageView's size. I am confused in using below assets.
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit,
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw
What to set in autoresize mask ?
How do they behave ?

Please try this code, Hope it will work for you.
set UIImageView contentMode to UIViewContentModeScaleAspectFill as below :
imageView.contentMode = UIViewContentModeScaleAspectFill;
set autoresizingMask of UIImageView as below :
imageView.autoresizingMask =
( UIViewAutoresizingFlexibleBottomMargin
| UIViewAutoresizingFlexibleHeight
| UIViewAutoresizingFlexibleLeftMargin
| UIViewAutoresizingFlexibleRightMargin
| UIViewAutoresizingFlexibleTopMargin
| UIViewAutoresizingFlexibleWidth );

You just need these two lines:
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.layer.clipsToBounds = YES; // Must do this or else image will overflow

Here a solution for swift:
let imageView = UIImageView(image: UIImage(named: "backgroundImage"))
imageView.frame = tableView.frame
imageView.contentMode = .ScaleAspectFill
tableView.backgroundView = imageView

If you want to make your UIImageView size according to ratio ,then you must set it's mode to UIViewContentModeScaleAspectFit
yourimage.contentMode=UIViewContentModeScaleAspectFit;
let me know it is working or not!!!
Happy Coding.

In swift you set content mode as well
var newImgThumb : UIImageView
newImgThumb = UIImageView(frame:CGRectMake(0, 0, 100, 70))
newImgThumb.contentMode = .ScaleAspectFit

Worth noting that swift 3 has changed as following
.ScaleAspectFit to scaleAspectFit
.ScaleAspectFill to .scaleAspectFill

Hope this helpful for you
CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
image = [UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);

Related

UIImage from object c to swift and image size bad

i've a PNG image that i would insert into my navigation title.
In Object C i've
UIImage *image = [UIImage imageNamed:#"logo_up.png"];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image];
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
it works very well and my image was in high quality
Then i create a similar APP in swift, using the same image, and write this code
self.navigationItem.titleView = UIImageView(image: UIImage(named: "icons/logo_up.png"))
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.frame.size.width = 320
self.navigationController?.navigationBar.frame.size.height = 44
it print my image but with very poor quality.
I create different image with different size but nothing change. Every image in this APP have poor quality.
I use PNG and JPG extension.
Try to play with the content mode of your UIImageView. You are changing the frame of the UINavigationBar in your Swift example, the image can be reduced in quality by doing this.
let imageView = UIImageView(image: UIImage(named: "icons/logo_up.png"))
imageView.contentMode = .ScaleAspectFit //change contentMode
self.navigationItem.titleView = imageView
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor() self.navigationController?.navigationBar.frame.size.width = 320
self.navigationController?.navigationBar.frame.size.height = 44

Display Top Portion of UIImageview

I'm trying to display a top portion of an UIImage.
I know I can use the following code and display the middle portion. I'm just trying to figure out how to do the same for the top portion:
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
The UIImage I get from the server is not necessarily the same size, so I cannot use UIViewContentModeTopLeft. I want a way to scale the image and show the top portion.
Thanks.
You want to display an arbitrary rectangle of your image, so the easiest way to go will to be to put your imageView inside a regular view. You can set the frame of the image view to display the bit you want and set the enclosing view to do the clipping.
e.g. you have a 1000 x 1000 px image and you want to display the rectangle 200,200 to 400,400
UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"SomeImage"]];
imageView.frame = CGRectMake( -200, -200, 1000, 1000);
UIView* enclosingView = [[UIView alloc] initWithFrame:CGRectMake( 0, 0, 200, 200);
enclosingView.clipsToBounds = YES;
[enclosingView addSubview: imageView];
Content mode doesn't matter much in this case, since you're setting the dimension of the image view to match the image.
One way is to call CGImageCreateWithImageInRect on your original image to create a new image with just the top portion.
Something like:
CGImageRef newImageRef = CGImageCreateWithImageInRect( oldImage.CGImage, CGRectMake(0,0,50,50) );
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease( newImageRef );
then display newImage rather than oldImage.

Image is not fit to the frame of UIImageView

I am creating the UIImageView using interface Builder. Its frame size is (320,67).
I want to display the image on the imageView. I am getting the image from the web. The problem is that the image get from web is stretched to display on the imageview...
Here my code
NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.isco.com/webproductimages/appBnr/bnr1.jpg"]];
imageView.image = [UIImage imageWithData:imageData];
Can anyone tel me that how to display the image fit to display on imageView????
Either use
imageView.contentMode = UIViewContentModeScaleAspectFill;
or
imageView.contentMode = UIViewContentModeScaleAspectFit;
The first one will fill the frame, possibly cutting off parts of your image. The second one will show the entire image, possibly leaving areas of the frame open.
For Swift :
imageView.contentMode = UIViewContentMode.ScaleAspectFit
For Objective-C :
imageView.contentMode = UIViewContentModeScaleAspectFit
ScaleAspectFit option is use to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining areas of the view’s bounds is transparent.
Refer Apple docs for details.
I ended up resizing the image after the image was scaled according to it's aspect ratio.
let widthRatio = ImageView.bounds.size.width / (captureImageView.image?.size.width)!
let heightRatio = ImageView.bounds.size.height / (captureImageView.image?.size.height)!
let scale = min(widthRatio, heightRatio)
let imageWidth = scale * (ImageView.image?.size.width)!
let imageHeight = scale * (ImageView.image?.size.height)!
ImageView.frame = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)
Try this code.
imView.contentMode = UIViewContentModeScaleAspectFit;

How to fill background image of an UIView

I have an UIView and I set a background image in this way:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"sfond-appz.png"]];
My problem is that back-image is not centered inside the view, but it's replayed some times to fill all the view. Is there a way to center image inside uiview and scretch to have screen size?
Note: I can't use UIImageView for background cause I have a scrollview.
You need to process the image beforehand, to make a centered and stretched image.
Try this:
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
For Swift use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "ImageName.png")?.draw(in: self.view.bounds)
if let image = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
}else{
UIGraphicsEndImageContext()
debugPrint("Image not available")
}
The colorWithPattern: method is really for generating patterns from images. Thus, the customization you require is most likely not possible, nor is it meant to be.
Indeed you need to use a UIImageView to center and scale an image. The fact that you have a UIScrollView does not prevent this:
Make self.view a generic view, then add both the UIImageView and the UIScrollView as subviews. Make sure all is wired up correctly in Interface Builder, and make the background color of the scroll view transparent.
This is IMHO the simplest and most flexible design for future changes.
Repeat:
UIImage *img = [UIImage imageNamed:#"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];
Stretched
UIImage *img = [UIImage imageNamed:#"bg.png"];
view.layer.contents = img.CGImage;
Correct way to do in Swift 4,
If your frame as screen size is correct then put anywhere otherwise,
important to write this in viewDidLayoutSubviews because we can get actual frame in viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
UIGraphicsBeginImageContext(view.frame.size)
UIImage(named: "myImage")?.draw(in: self.view.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
view.backgroundColor = UIColor.init(patternImage: image!)
}
For Swift 2.1 use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "Cyan.jpg")?.drawInRect(self.view.bounds)
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
You can use UIGraphicsBeginImageContext method to set the size of image same that of view.
Syntax : void UIGraphicsBeginImageContext(CGSize size);
#define IMAGE(imageName) (UIImage *)[UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:imageName ofType:IMAGE_TYPE_PNG]]
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#“MyImage.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:IMAGE(#"mainBg")];
For Swift 3.0 use the following code:
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "bg.png")?.drawAsPattern(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
The marked answer is fine, but it makes the image stretched.
In my case I had a small tile image that I wanted repeat not stretch.
And the following code was the best way for me to solve the black background issue:
UIImage *tileImage = [UIImage imageNamed:#"myTileImage"];
UIColor *color = [UIColor colorWithPatternImage:tileImage];
UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.frame];
[backgroundView setBackgroundColor:color];
//backgroundView.alpha = 0.1; //use this if you want to fade it away.
[self.view addSubview:backgroundView];
[self.view sendSubviewToBack:backgroundView];
Swift 4 Solution :
#IBInspectable var backgroundImage: UIImage? {
didSet {
UIGraphicsBeginImageContext(self.frame.size)
backgroundImage?.draw(in: self.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image{
self.backgroundColor = UIColor(patternImage: image)
}
}
}

UIImageView change Width and Height

I've read various posts on here asking similar questions... I've tried various ways that were posted including bounds and frames etc. including the following:
myImage.frame = CGRectMake(0.0f, 0.0f,50.0f, 50.0f);
and:
myImage.bounds = CGRectMake(0.0f, 0.0f,50.0f, 120.0f);
neither of those work.
However, I find it interesting that the following code let's me move the Image around but doesn't change the width:
CGRect frameRect = myImage.frame;
frameRect.size.width = 50.0f;
frameRect.origin.x += 10.5f;
myImage.frame = frameRect;
So why don't any of these change the width/height of my ImageView?
I found another post on here that basically states I have to right a small book of code to get it resize my image... is that true?
Such as this one:
UIImage: Resize, then Crop
certainly this is simpler than that??
The following will change the size of the UIImaveView, clipping the underlying image without resizing it and keeping it aligned to bottom left of view:
imageView.frame = CGRectMake(
imageView.frame.origin.x,
imageView.frame.origin.y, newWidth, newHeight);
imageView.contentMode = UIViewContentModeBottomLeft; // This determines position of image
imageView.clipsToBounds = YES;
First off, you can't set the frame or bounds of the UIImage - that will only work on a UIImageView.
I've found that changing the frame of a UIImageView causes the Image to be scaled to the new size. Sometimes, that's undesirable - and you want instead to crop the image.
I can't tell if this is what you're asking for, but here's some code to crop an image to a specific size in a UIImageView:
UIImage *myImage = [UIImage imageNamed:#"photo.png"];
CGRect cropRect = CGRectMake(0.0, 0.0, 320.0, 44.0));
CGImageRef croppedImage = CGImageCreateWithImageInRect([myImage CGImage], cropRect);
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:cropRect];
[myImageView setImage:[UIImage imageWithCGImage:croppedImage]];
CGImageRelease(croppedImage);
From what I get of the question, the OP wanted to change the size of the UIImageView when the size of the container UIView is changed. The code below will do it...
UIView * foo = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)] autorelease];
foo.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
UIImageView * bar = [[UIImageView alloc] initWithImage:
[UIImage imageNamed:#"test.png"]];
bar.autoresizingMask = foo.autoresizingMask;
[foo addSubview:bar];
[self.view addSubview:foo];
The key here are the foo.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight and the bar.autoresizingMask = foo.autoresizingMask; lines. Forget either of these, and the whole jigmarole will stop working.
Well, if your read the documentation about UIIMage you can notice that is impossible to change any parameter of an UIImage after create it, the solution I've implemented for use high quality images for change some parameter of (for example) the SliderControl as Screw Image, is the next one:
UIImage *tumbImage= [UIImage imageNamed:#"screw.png"];
UIImage *screw = [UIImage imageWithData:UIImagePNGRepresentation(tumbImage) scale:2];
With that, I can to use 100x100 px image in my apps scaled to 50%.
Kind regards.
Try Using a UIScrollView. Add the UIImageView to the UIScrollView in Interface Builder you can then control the position and size of the image as follows:
CGRect rect = [scrollView frame];
rect.origin.x = 50.0f;
rect.origin.y = 0.0f;
rect.size.width = 320.0f;
rect.size.height = 150.0f;
[scrollView setFrame:rect];
If you tried those methods cannot work, the only way to do it is to add the constraint of width and height to the UIImageView.
// Create the constraint in code
NSLayoutConstraint *constraint0 = [NSLayoutConstraint constraintWithItem: myImage attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0f constant: yourNewsWidth];
NSLayoutConstraint *constraint1 = [NSLayoutConstraint constraintWithItem: myImage attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0f constant: yourNewsHeight];
[myImage addConstraint:constraint0];
[myImage addConstraint:constraint1];
Use myImageView.frame = myNewPosAndSize; to resize or reposition your image view (as with any other view). It might confuse you that the image view draws its image with its original size, possibly exceeding its own dimensions. To disable this use myImageView.clipsToBounds = NO;
You don't have to write a whole book, you can copy that code.
I believe the UIImageView always draws the image at 0,0 at a 1.0 scale. You'll need to resize the image if you want to continue using the UIImageView.