Resize UIImage to 200x200pt/px
Here is my code. The Image is in width 850 px and not 200 px:
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
@IBAction func chooseImage(sender: AnyObject) {
var myPickerController = UIImagePickerController()
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
myPickerController.delegate = self;
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
var imagenow = info[UIImagePickerControllerOriginalImage] as? UIImage
imageImage.image = resizeImage(imagenow!, newWidth: 200)
pimg2 = imageImage.image!
cidnew2 = textFieldCID!.text!
pname2 = textFieldName!.text
pmanu2 = textFieldMan!.text
pnick2 = textFieldNick!.text
podate2 = textFieldPODate!.text
pno2 = textFieldArtNo!.text
self.dismissViewControllerAnimated(true, completion: nil)
}
The simplest way to resize an UIImage?
The simplest way is to set the frame of your UIImageView
and set the contentMode
to one of the resizing options.
Or you can use this utility method, if you actually need to resize an image:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Example usage:
#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];
The simplest way to resize an UIImage?
The simplest way is to set the frame of your UIImageView
and set the contentMode
to one of the resizing options.
Or you can use this utility method, if you actually need to resize an image:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Example usage:
#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];
Proportionally resize UIImage by width
Check this blog post out. In particular, these two files:
- UIImage+Resize.h
- UIImage+Resize.m
Maybe this would work for you:
UIImage *image = [UIImage imageNamed:@"SomeImage-900x675"]; // SomeImage-900x675.png
CGFloat targetWidth = 400.0f;
CGFloat scaleFactor = targetWidth / image.size.width;
CGFloat targetHeight = image.size.height * scaleFactor;
CGSize targetSize = CGSizeMake(targetWidth, targetHeight);
UIImage *scaledImage = [image resizedImage:targetSize interpolationQuality:kCGInterpolationHigh];
Resize UIImage to fit device width
It depends on what you really want.
If you need "aspect fit", you need to either drop your image into a UIImageView like emresancaktar provided. The issue with this - and by your use of the view's backgroundColor you suggest this - is that you wish to put things on top of said UIImageView. This is complicating things.
If you just need to scale to the view size with no regard to "aspect fit", you can use it's layer:
view.layer.contents = UIImage(named: "bg_sunrise")?.cgImage
Finally, if your like using a view's layer but do need "aspect fit", you'll need to work with a CGImage context, possibly using the UIImage.drawInRect() method after making some calculations. A quick search on "CALayer draw image aspect fit" yielded this gist. It's a little old but there's a Swift version there. You can cobble what you need to return a CALayer instead of a UIImage.
The simplest way to resize an UIImage?
The simplest way is to set the frame of your UIImageView
and set the contentMode
to one of the resizing options.
Or you can use this utility method, if you actually need to resize an image:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Example usage:
#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];
How to scale down a UIImage and make it crispy / sharp at the same time instead of blurry?
Merely using imageWithCGImage
is not sufficient. It will scale, but the result will be blurry and suboptimal whether scaling up or down.
If you want to get the aliasing right and get rid of the "jaggies" you need something like this: http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/.
My working test code looks something like this, which is Trevor's solution with one small adjustment to work with my transparent PNGs:
- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;
}
Changing the size and location of a UIImage within UIImageView (swift)
If you want to create a 2nd image with size 100,100 and add this image to the previous UIImageView
you can do this:
let imageName = "house.png"
let originalImage = UIImage(named:imageName)!
let imageView = UIImageView(image: originalImage)
// this is only to visualization purpose
imageView.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(imageView)
// create a new image resizing it
let destinationSize = CGSizeMake(100, 100)
UIGraphicsBeginImageContext(destinationSize);
originalImage.drawInRect(CGRectMake(0,0,destinationSize.width,destinationSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
// add the new image to the UIImageView
imageView.image = newImage
imageView.contentMode = UIViewContentMode.Center
Related Topics
How to Achieve a "Clock Wipe"/ Radial Wipe Effect in iOS
Combine Framework: How to Process Each Element of Array Asynchronously Before Proceeding
Cannot Change Search Bar Background Color
How to Find File Uti for File, Withouth Pathextension, in a Path in Swift
Arkit - Apply Cifilter to a Specific Vertices of Arfaceanchor
Ios: Serialize/Deserialize Complex JSON Generically from Nsobject Class
How to Overload an Assignment Operator in Swift
Parsing Nested Array of Dictionaries Using Object Mapper
How to Set the Title of a Uibutton as Left-Aligned
Lldb (Swift): Casting Raw Address into Usable Type
Cocoapods - 'Pod Install' Takes Forever
How to Draw a Transparent Uitoolbar or Uinavigationbar in iOS7
Add Bottom Border Line to UI Textfield View in Swiftui/Swift/Objective-C/Xamarin
Uicollectionview: Must Be Initialized with a Non-Nil Layout Parameter
Detecting Collisions in Sprite Kit
Load View from an External Xib File in Storyboard