Ответ прост. Код сработал. Он добавил закругленные углы к объекту UIImageView, и maskToBounds работал хорошо.
Но фактическое отображаемое изображение меньше. Я использовал AspectFit в качестве режима, чтобы фактическое изображение не сжималось, а отображалось в исходном соотношении сторон. Из-за более длинной компоновки размеров iPhone5 изображение заполнило только часть принадлежащего ему UIImageView. Я изменил цвет фона на серый для скриншота, и теперь он становится ясным.
Таким образом, решение будет заключаться в том, что мне придется рассчитать правильный размер изображения, чтобы он точно соответствовал размеру масштабированного изображения. Тогда это должно работать.
(Я обновлю этот ответ, когда это будет сделано).
![введите здесь описание изображения](https://i.stack.imgur.com/0PD3o.png)
Обновление: это то, что я наконец сделал: я удалил UIImageView из раскадровки и обработал его программно.
Не смущайтесь сложностью. Я добавил еще один вид, чтобы отбросить тень, хотя это не связано с исходным вопросом. Тень, которую я все равно хотел добавить. И оказалось, что тень CALayer и masksToBounds=YES
не совсем совпадают. Вот почему я добавил обычный UIView, который находится между представлением карты и фоновым представлением.
Наконец, отображение простого прямоугольного изображения настолько утомительно, что я думаю, что просто создать подкласс UIView и отрисовать все с помощью openGL или около того непосредственно в CALayer, вероятно, было бы намного проще. :-)
Во всяком случае, это мой код:
- (void)viewDidLoad {
[super viewDidLoad];
self.state = @0;
// Create an image view to carry the image with round rects
// and create a regular view to create the shadow.
// Add the shadow view first so that it appears behind
// the actual image view.
// Explanation: We need a separate view for the shadow with the same
// dimenstions as the imageView. This is because the imageView's image
// is rectangular and will only be clipped to round rects when the
// property masksToBounds is set to YES. But this setting will also
// clip away any shadow that the imageView's layer may have.
// Therfore we add a separate mainly empty UIView just behind the
// UIImageview to throw the shadow.
self.shadowV = [[UIView alloc] init];
self.imageV = [[UIImageView alloc] initWithImage:self.image];
[self.view addSubview:self.shadowV];
[self.shadowV addSubview:self.imageV];
// set the raidus and the mask to follow the rounded corners.
[self.imageV.layer setCornerRadius:CORNER_RADIUS];
[self.imageV.layer setMasksToBounds:YES];
[self.imageV setContentMode:UIViewContentModeScaleAspectFit];
// set the shadows properties
[self.shadowV.layer setShadowColor:[UIColor blackColor].CGColor];
[self.shadowV.layer setShadowOpacity:0.4];
[self.shadowV.layer setShadowRadius:3.0];
[self.shadowV.layer setShadowOffset:CGSizeMake(SHADOW_OFFSET, SHADOW_OFFSET)];
[self.shadowV.layer setCornerRadius:CORNER_RADIUS];
[self.shadowV setBackgroundColor:[UIColor whiteColor]]; // The view needs to have some content. Otherwise it is not displayed at all, not even its shadow.
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Just to be save
if (!self.image) {
return;
}
self.imageV.image = self.image; // The image property was set by the caller.
// Layout imageV within self.view with a margin of MARGIN
self.imageV.frame = CGRectMake(MARGIN, MARGIN, self.view.bounds.size.width - 2 * MARGIN, self.view.bounds.size.height - 2 * MARGIN);
// Calculate the size and position of the image and set the image view to
// the same dimensions
// This works under the assumption, that the image content mode is aspectFit.
// Well, as we are doing so much of the layout manually, it would work with a number of content modes. :-)
float imageWidth, imageHeight;
float heightWidthRatioImageView = self.view.frame.size.height / self.view.frame.size.width;
float heightWidthRatioImage = self.image.size.height / self.image.size.width;
if (heightWidthRatioImageView > heightWidthRatioImage) {
// The ImageView is "higher" than the image itself.
// --> The image width is set to the imageView width and its height is scaled accordingly.
imageWidth = self.imageV.frame.size.width;
imageHeight = imageWidth * heightWidthRatioImage;
} else {
// The ImageView is "wider" than the image itself.
// --> The image height is set to the imageView height and its width is scaled accordingly.
imageHeight = self.imageV.frame.size.height;
imageWidth = imageHeight / heightWidthRatioImage;
}
// Layout imageView and ShadowView accordingly.
CGRect imageRect =CGRectMake((self.view.bounds.size.width - imageWidth) / 2,
(self.view.bounds.size.height - imageHeight) / 2,
imageWidth, imageHeight);
[self.shadowV setFrame:imageRect];
[self.imageV setFrame:CGRectMake(0.0f, 0.0f, imageWidth, imageHeight)]; // Origin is (0,0) because it overlaps its superview which just throws the shadow.
}
И вот как это наконец выглядит: ![введите здесь описание изображения](https://i.stack.imgur.com/lviMc.png)
![введите здесь описание изображения](https://i. stack.imgur.com/aQB7w.png)
person
Hermann Klecker
schedule
30.03.2014
frame
, вы должны говоритьbounds
- фрейм представления изображения позиционируется относительно границыself.view
, а не его фрейма. - person matt   schedule 30.03.2014