Resize image and maintain its aspect ratio in iOS - ios

I am trying to select an image from photo library, this is the photo which I have downloaded from net and is stored in my photo lib.
So now I want to give user an option to select an image from photo lib and apply as a backgroundImage throught my app, but when I do it, I get the image this way on my iphone screen
Actually the image has been filled the screen, because the content mode specified is "scaleToFill".
1) I want to know how to make this image maintain its aspect ratio and also fill the screen?
Regards
Ranjit

check this blog. use these two files
UIImage+Resize.h
UIImage+Resize.m
UIImage *image = [UIImage imageNamed:#"SomeImage-900x675"]; // SomeImage-900x675.png
CGFloat targetWidth = 320.0;
CGFloat scaleFactor = targetWidth / image.size.width;
CGFloat targetHeight = image.size.height * scaleFactor;
CGSize targetSize = CGSizeMake(targetWidth, targetHeight);
UIImage *scaledImage = [image resizedImage:targetSize interpolationQuality:kCGInterpolationHigh];

though your image is taking all the screen size, Your image size is biger...You will try by scaling image with following resolutions
320*480,
640*960,
1240*2208

Related

How to get image without resizing?

first of all i need to describe what i gonna to do:
i need to display a header image with full screen width for all devices.
there for i should provide multiple pictures with different sizes, and not just 2x and 3x.
so i would have these images:
header_width_1242.png for iphone 6 plus.
header_width_1125.png for iphone 6 plus display zoom
header_width_640.png for iphone 5,6
...
so i shouldn't choose image according to the scale, rather i should choose image according to the width:
let image_name = "header_width_" + String(UIScreen.mainScreen().scale * UIScreen.mainScreen().bounds.width)
let image = UIImage(named:image_name)
the problem, that ios scale the image automatically again. so if the device with scale 2x. then it return the image * 2 size.
e.g : for iphone 5 which has width 320 and scale 2, i need the header_width_640.png , but it seems that the system scale the image to 1280 (640 * 2).
How could i tell the system, to return image UIImage(named:image_name) without scaling ?thanks
You could declare a screenSize property on your viewController.
// Determine screen size
let screenSize: CGRect = UIScreen.mainScreen().bounds
Then, when you need to set an image, you could do the following:
if screenSize.width < 641 {
// set your imageView to the image for 640 screen width
} else if screenSize.width < 1126 {
// set your imageView to the image for 1125 screen width
} else if screenSize.width < 1243 {
// set your imageView to the image for 1242 screen width
}
You should not constraint assets by screen size, is better if you do by using size classes if available. Image assets directory make this possible in the inspector panel, by choosing the size classes for each image.
I do understand that sometimes is a need, but try to think in a relative perspective. If the image is something like a logo aligned by left or right you can use slicing to create stretchable end/beginning on the image.
If the image is center with a solid color or something drawable by code you can draw it at run time.
Here is a snippet in ObjC that use in an app of mine you can easily convert in SWIFT:
-(UIImage*) createNavBarBackgroundWithImage:(UIImage*) image {
CGSize screenSize = ((CGRect)[[UIScreen mainScreen] bounds]).size;
CGFloat width = screenSize.width;
CGFloat height = 64.0;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0);
//Draw background
UIColor * backGroundColor = [UIColor colorWithRed:27.f/255.f green:142.f/255.f blue:138.f/255.f alpha:1.0];
[backGroundColor setFill];
UIRectFill(CGRectMake(0, 0, width, height));
//Draw the image at the center
CGPoint point = CGPointMake(width/2 - image.size.width/2, 0);
[image drawAtPoint:point];;
UIImage *newBGImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newBGImage;
}
Use Image Asset
https://developer.apple.com/library/ios/recipes/xcode_help-image_catalog-1.0/chapters/AddingImageSets.html
header_width_1242.png for iphone 6 plus. Name it header_width_414.png drag to 3x
header_width_1125.png name it header_width_375.png drag to 3x
header_width_640.png name it header_width_320.png drag to 2x
let image_name = "header_width_" + UIScreen.mainScreen().bounds.width)
let image = UIImage(named:image_name)

Set image in UIImageView with original Dimension in ios

My UIImageView with constant Width*Height is 100*100 on UIView, But image i want to show in this UIImageView is 25*25 (original dimension ).
I don't want to stretch image. i try UIImageView ContentMode property but did't work.
This i don't want.tried sizeToFit and aspectCenter mode.
I need following result,For small images
How to do that(With out stretching original image dimension and constant UIImageView dimension).What will be case if image is bigger than UIImageView ? Thanks in advance.
Try this
(Objective-C):
imageView.contentMode = UIViewContentModeCenter;
(Swift):
imageView.contentMode = UIViewContentMode.Center;
Call - sizeToFit
That should do exactly what you need.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/sizeToFit
you should try this
imageView.contentMode = UIViewContentModeScaleAspectFit;
no matter image is small or big it will scale the image.
if you don't want to stretch image than you have to resize UIImageView to image size
You can obtain image size from UIImage.
for eg
UIImage *image = [UIImage imageNamed:#"imageName"];
float imgHeight = image.size.height;
float imgWidth = image.size.width;

Trying to crop my UIImage to a 1:1 aspect ratio (square) but it keeps enlarging the image causing it to be blurry. Why?

Given a UIImage, I'm trying to make it into a square. Just chop some of the largest dimension off to make it 1:1 in aspect ratio.
UIImage *pic = [UIImage imageNamed:#"pic"];
CGFloat originalWidth = pic.size.width;
CGFloat originalHeight = pic.size.height;
float smallestDimension = fminf(originalWidth, originalHeight);
CGRect square = CGRectMake(0, 0, smallestDimension, smallestDimension);
CGImageRef imageRef = CGImageCreateWithImageInRect([pic CGImage], square);
UIImage *squareImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
UIImageView *imageView = [[UIImageView alloc] initWithImage:squareImage];
imageView.frame = CGRectMake(100, 100, imageView.bounds.size.width, imageView.bounds.size.height);
[self.view addSubview:imageView];
But this is what it results in:
When it should look like this, but just a little narrower.
Why is this? The images are pic(150x114) / pic#2x(300x228).
The problem is you're mixing up logical and pixel sizes. On non retina devices these two are the same, but on retina devices (like in your case) the pixel size is actually double the logical size.
Usually, when designing your GUI, you can always just think in logical sizes and coordinates, and iOS (or OS X) will make sure, that everything is doubled on retina screens. However, in some cases, especially when creating images yourself, you have to explicitly specify what size you mean.
UIImage's size method returns the logical size. That is the resolution on non-retina screens for instance. This is why CGImageCreateWithImageInRect will only create an new image, from the upper left half of the image.
Multiply your logical size with the scale of the image (1 on non-retina devices, 2 on retina devices):
CGFloat originalWidth = pic.size.width * pic.scale;
CGFloat originalHeight = pic.size.height * pic.scale;
This will make sure, that the new image is created from the full height (or width) of the original image. Now, one remaining problem is, that when you create a new UIImage using
UIImage *squareImage = [UIImage imageWithCGImage:imageRef];
iOS will think, this is a regular, non-retina image and it will display it twice as large as you would expect. To fix this, you have to specify the scale when you create the UIImage:
UIImage *squareImage = [UIImage imageWithCGImage:imageRef
scale:pic.scale
orientation:pic.imageOrientation];

Image Cropping from Gallery

I want to crop selected image from a gallery (Programmatically). I have done a lot of research and got the [tutor](http://iosdevelopertips.com/graphics/how-to-crop-an-image.html) gone through this.still getting confuse whether cropping of image can be done by using UIImagePickerController or UIImageView.I'm not getting from where to start or how to start?. please suggest me the right way any one.
Answer : CGImage Reference
1) Create a rectangle that represents a cropped image from the middle of the existing image :
CGRect rect = CGRectMake(size.width / 4, size.height / 4 ,
(size.width / 2), (size.height / 2));
2) Create bitmap image from original image data, using rectangle to specify desired crop area :
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
3) Create and show the new image from bitmap data :
imageView = [[UIImageView alloc] initWithImage:img];
Useful Links :
1) Working with UIGestureRecognizers.
2) Cropping and Resizing Images from Camera in iOS and Objective-C.
GoodLuck !!!

Reduce pdf size - Objective c

I have a pdf generation project, it consist of some texts and an image which is already stored in db, i want to preview and mail the pdf generated, everything is ok when there is only text data.
Problem arises if there is image in our data. The mail receives
the pdf of size 10MB or above even if it have image of size 1MB or below.It is working fine in simulator.My code to draw image is shown below:
UIImage *plotImage=[[UIImage alloc]initWithContentsOfFile:[localPictureArray objectAtIndex:i]];
CGSize imageSize=plotImage.size;
CGFloat scaleFactor = 1.0;
if (imageSize.height>(maxHeight-currentPageY) || imageSize.width>maxWidth )
{
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
currentPageY = kMargin;
if (!((scaleFactor = (maxWidth / imageSize.width)) > ((maxHeight-currentPageY) / imageSize.height)))
{
scaleFactor = (maxHeight-currentPageY) /imageSize.height;
// scale to fit heigth.
}
CGRect rect = CGRectMake(kMargin,currentPageY,
imageSize.width * scaleFactor, imageSize.height * scaleFactor);
//Draw the image into the rect
[plotImage drawInRect:rect];
}
else
{
plotImage drawInRect:normal size)];//Normal size we need
NSLog(#"%#",NSStringFromCGSize(plotImage.size));
}
Since iam a starter iam struggling to solve it.
I struggled a lot.. at last when wrote image in jpeg format to pdf page using below code, size got reduced ten times!! Don't know it is the right method...
UIImage *lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(plotImage, 0.02)];
Instead of resizing the rect in the context, You need to change the CTM (Current Transform Matrix).
CGContextSaveGState(theContext);
CGContextScaleCTM(theContext, scaleFactor, scaleFactor);
... Drawing commands here ...
CGContextRestoreGState(theContext);
(http://macdevcenter.com/pub/a/mac/2004/11/02/quartz.html)

Resources