I have only ever used auto layout in IB and was wondering how I can go about programatically setting a UIImageView to centre both vertically and horizontally after resizing it.
Basically the UIImageView contains a photo and the UIImageView is then resized to fit the photo. After this process I was wondering how I can go about setting the constraints so that the image is correctly positioned.
The code below shows the process of loading the image and setting the UIImageView. At the minute the positioning is done manually without the use of AutoLayout.
- (void)setupUI {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
self.imageViewCanvas.translatesAutoresizingMaskIntoConstraints = YES;
[self.imageViewCanvas setFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
self.btnTool.alpha = 0;
}
- (void)loadNewImageIntoCanvas {
[self.imageViewCanvas setImage:self.imageToEdit];
[self imageSizeAfterAspectFit:self.imageViewCanvas];
[UIImageView animateWithDuration:0.2 animations:^{
self.imageViewCanvas.alpha = 1;
} completion:^(BOOL finished) {
[self showBTNTool];
}];
}
- (void)resetCanvasSize {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
[self.imageViewCanvas setFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
}
-(CGSize)imageSizeAfterAspectFit:(UIImageView*)imgview{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGRect newSize = [self frameForImage:self.imageViewCanvas.image inImageViewAspectFit:self.imageViewCanvas];
float newwidth = newSize.size.width;
float newheight = newSize.size.height;
float new_x = (screenWidth / 2) - (newwidth / 2);
float new_y = (screenHeight / 2) - (newheight / 2);
[self.imageViewCanvas setFrame:CGRectMake(new_x, new_y, newwidth, newheight)];
return CGSizeMake(0, 0);
}
-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView {
float imageRatio = image.size.width / image.size.height;
float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
if(imageRatio < viewRatio)
{
float scale = imageView.frame.size.height / image.size.height;
float width = scale * image.size.width;
float topLeftX = (imageView.frame.size.width - width) * 0.5;
return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
}
else
{
float scale = imageView.frame.size.width / image.size.width;
float height = scale * image.size.height;
float topLeftY = (imageView.frame.size.height - height) * 0.5;
return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
}
}