Fit FULL image in 612x612 size for Instagram while keeping ratio

假如想象 提交于 2019-12-04 18:38:36

This will create a full screen image for posting on Instagram for images that have heights greater than their widths.

UIImage *originalImage = [UIImage imageNamed:@"lion.jpg"];

// Create rect with height and width equal to originalImages height
CGSize size = CGSizeMake(originalImage.size.height, originalImage.size.height);
UIGraphicsBeginImageContextWithOptions(size, YES, 0);
// Fill the background with some color
[[UIColor lightGrayColor] setFill];
UIRectFill(CGRectMake(0, 0, size.width, size.height));
// Create image for what we just did
UIImage *bgImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIGraphicsBeginImageContext(bgImage.size);
// Take originalImage and center it in bgImage
// We get the center of bgImage by (bgImage.size.width / 2)
// But the coords of the originalImage start at the top left (0,0)
// So we need to subtract half of our orginalImages width so that it centers (bgImage.size.width / 2) - (originalImage.size.width / 2)
[originalImage drawInRect:CGRectMake((bgImage.size.width / 2) - (originalImage.size.width / 2), 0, originalImage.size.width, originalImage.size.height)];
// Create image for what we just did
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Set your finalImage to a UIImageView or send it to Instagram
[self.final setImage:finalImage];

To make this work for images with widths greater than their heights you would just set the CGSize size to originalImages.size.width. Then to center it for the finalImage just change the equation to calculate for height rather than width.

I just create an image view with content mode set to aspect fit then screenshot that image view.. if anyone else has a more elegant solution let me know

                    UIImageView *imageview = [[UIImageView alloc] init];
                    imageview.contentMode = UIViewContentModeScaleAspectFit;
                    imageview.frame = CGRectMake(0, 0, 612, 612);
                    imageview.clipsToBounds = NO;
                    imageview.image = viewImage;

                   CGSize imageSize = CGSizeMake(imageview.bounds.size.width, imageview.bounds.size.height);
                    UIGraphicsBeginImageContext(imageSize);
                    [imageview.layer renderInContext:UIGraphicsGetCurrentContext()];
                    viewImage = UIGraphicsGetImageFromCurrentImageContext();
                    UIGraphicsEndImageContext();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!