Reputation: 1973
I have this code, I take a photo with this size 2448x3264 and i need resize and adjust to display of screen at the top left. sorry for my english thanks
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];
NSLog(@"%f",imagenUsr.size.height); //2448px
NSLog(@"%f",imagenUsr.size.width); //3264px
}
I need adjust to 320x568 aspect to fill at the top and left of the image taken
Upvotes: 9
Views: 23685
Reputation: 3383
Swift 3.0 / 4.0
AspectFill image cropping/Resizing... according to UIImageview Frame Size.
func ResizeImage(with image: UIImage?, scaledToFill size: CGSize) -> UIImage? {
let scale: CGFloat = max(size.width / (image?.size.width ?? 0.0), size.height / (image?.size.height ?? 0.0))
let width: CGFloat = (image?.size.width ?? 0.0) * scale
let height: CGFloat = (image?.size.height ?? 0.0) * scale
let imageRect = CGRect(x: (size.width - width) / 2.0, y: (size.height - height) / 2.0, width: width, height: height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
image?.draw(in: imageRect)
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Upvotes: 15
Reputation: 9835
EDIT: Not sure if I missed this or it was edited, but I didn't see that you wanted to crop it as well. Rashad's solution should work for you.
Have you tried creating an image view with the image and adding it to the view?
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
imageView.image = imagenUsr;
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:imageView];
}
Upvotes: 3
Reputation: 11197
Try this:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];
double width = imagenUsr.size.width;
double height = imagenUsr.size.height;
double screenWidth = self.view.frame.size.width;
double apect = width/height;
double nHeight = screenWidth/ apect;
self.imgView.frame = CGRectMake(0, 0, screenWidth, nHeight);
self.imgView.center = self.view.center;
self.imgView.image = imagenUsr;
}
This will help you keeping the aspect ratio as before.
Another way would be:
self.imgView.contentMode = UIViewContentModeScaleAspectFit;
self.imgView.image = imagenUsr;
Hope this helps.. :)
Upvotes: 12