简体   繁体   English

如何使用自动调整蒙版对UIImageView进行取整?

[英]How to round an UIImageView with Autoresizing Masks?

Hello everyone. 大家好。 I am creating an iOS app. 我正在创建一个iOS应用。 In which I have got an ImageView on UITableView cell. 在其中我在UITableView单元格上有一个ImageView。 The problem is whenever I am making it circular by dividing its height or width by 2 its creating an oval. 问题是,每当我通过将其高度或宽度除以2(即创建一个椭圆形)使其变为圆形时,就会出现问题。 Although when I am removing the autoresizing its working fine. 虽然当我删除自动调整大小的工作正常。 Can anybody please help here. 有人可以帮忙吗?

I have found with UITableViewCell that you get strange affects related to size classes when you show rounded images in cells. 我发现使用UITableViewCell时,在单元格中显示圆形图像时,会得到与尺寸类相关的奇怪影响。 This is especially the case if you use different size constraints for images on iPad say versus iPhone. 如果您对iPad和iPhone上的图像使用不同的尺寸限制,则尤其如此。 To fix this I add the following to my cell class. 为了解决这个问题,我将以下内容添加到我的单元格类中。 self.myImageView is my cells UIImageView that I want to be round. self.myImageView是我想要显示的单元格UIImageView。

This also makes sure you pick up the latest changes in the image frame if it changes during layout. 这还可以确保您在布局期间更改图像帧中的最新更改。

- (void) layoutSubviews
{
    [super layoutSubviews];

    //
    // Make the image round using the latest frame size.
    //
    CALayer *l=[self.myImageView layer];
    [l setMasksToBounds:YES];
    [l setCornerRadius:self.myImageView.frame.size.width/2];

    // No border just now
    [l setBorderWidth:0.0];
    [l setBorderColor:[[UIColor blackColor] CGColor]];
}

Code assumes the image is square which it needs to be to work. 代码假定图像是正方形,它必须起作用。

是的,您应该给UIImageview的宽度和高度等于UITableviewcell的高度,然后将其除以二...

Add this generic method: 添加此通用方法:

func addRoundedCorner(viewToRound:UImageView, radius:CGFloat) {

    var layer:CALayer = viewToRound.layer;
    layer.cornerRadius=radius
    layer.masksToBounds = true
} //F.E.

Pass your imageview like this: 这样传递您的imageview:

self.addRoundedCorner(YourUImageView, radius:CGFloat(YourUImageView.frame.size.width/2.0))

Note: Apply it with proper auto resizing else it will not work fine Thanks 注意:应用适当的自动调整大小,否则将无法正常工作,谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM