2015-11-25 3 views
0

Я только когда-либо использовал автоматическую компоновку в IB и задавался вопросом, как я могу программно установить UIImageView для центрирования как по вертикали, так и по горизонтали после изменения размера.Программный центр UIImageVIew с использованием автоматической компоновки после изменения размера

В основном UIImageView содержит фотографию, а UIImageView затем изменяется в соответствии с фотографией. После этого процесса мне стало интересно, как я могу установить ограничения, чтобы изображение правильно позиционировалось.

В приведенном ниже коде представлен процесс загрузки изображения и установки UIImageView. В минуту позиционирование выполняется вручную без использования 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); 
} 
} 
+0

Почему бы вам просто не сказать self.imageViewCanvas.translatesAutoresizingMaskIntoConstraints = YES; затем установите его в рамку? – beyowulf

+0

Я делаю это сейчас, но получаю предупреждающие сообщения, когда запускаю приложение. По строкам «Невозможно одновременно удовлетворить ограничения». Обновленный вопрос, чтобы показать, как я это делаю. – ORStudios

+0

В результате получилось, что изображение находится не в нужном месте? – beyowulf

ответ

3

Для того, чтобы центра изображения с помощью автоматического макета вам нужны ограничения для ширины и высоты тоже. Не только centerXAnchor и centerYAnchor. Потому что UIImageView не имеет встроенного содержимого.

(Обратите внимание, что centerXAnchor и centerYAnchor методы доступны только прошивкой 9.0+)

self.imageView.translatesAutoresizingMaskIntoConstraints = NO; 

[self.imageView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES; 
[self.imageView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES; 

[self.imageView.widthAnchor constraintEqualToConstant:self.imageWidth].active = YES; 
[self.imageView.heightAnchor constraintEqualToConstant:self.imageHeight].active = YES; 
1

Довольно уверен, что вы можете сказать что-то вроде этого.

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.imageViewCanvas attribute: NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]]; 

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.imageViewCanvas attribute: NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]]; 

Этого недостаточно, чтобы удовлетворить все необходимые ограничения. ИМО, проще установить ограничения в IB, если вам нужно динамически изменять ограничения, создать для них IBOutlet и изменить их постоянное свойство.

Например, вы можете создать один IBOutlet для высоты ограничения вашего Просмотр изображения, вызовите его imageViewHeightConstraint, другой для ширины ограничения вашего Просмотр изображения, вызовите его imageViewWidthConstraint, то вы можете сказать:

self.imageViewHeightConstraint.constant = 400; 
self.imageViewWidthConstraint.constant = 400; 
+0

Является ли постоянное свойство размером? Так что, если я изменю его так, что новый UIImageView позволяет сказать 400 х 400, то константа будет 400? – ORStudios

Смежные вопросы