UIImageView的边框和圆角与图片从边缘弹出

4
我正在尝试制作一个带有圆角和白色边框的UIImageView,我已经子类化了一个UIImageView,这是代码:
MyUIImageView.h
@interface MyUIImageView : UIImageView

@end

MyUIImageView.m

@implementation MyUIImageView

-(void)layoutSubviews
{
    self.layer.cornerRadius = CGRectGetWidth(self.frame)/2.f;
    self.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.layer.borderWidth = kLineWidth;
    self.layer.masksToBounds = YES;
    self.clipsToBounds = YES;
    self.contentMode = UIViewContentModeScaleAspectFill;
    self.backgroundColor = [UIColor colorWithRed:0.82 green:0.82 blue:0.83 alpha:1];
}

@end

这是结果:

enter image description here

看起来很好,但是从这里可以看出有一个问题:

enter image description here

图片从边框边缘弹出,我该如何避免这个问题?我怎样才能将图像准确地剪切到边框的边缘?
2个回答

4
也许更好的解决方案并不需要创建另一个视图 - 有了两个视图,你会极大地增加动画等复杂性,更不用说跟踪和操作两个视图所需的开销了。
我会创建一个形状层,并将其添加为子层。像这样:
CAShapeLayer border = [[CAShapeLayer alloc] init];
border.path = [UIBezierPath bezierPathWithRoundedRect: self.bounds cornerRadius: self.layer.cornerRadius];
border.strokeColor = [UIColor whiteColor];
border.fillColor = [UIColor clearColor];
self.layer.addSublayer(border)

通过这种方式的好处是,如果您希望,您可以将其添加为UIImageView子类的一种方法。您可以向对象添加边框并忘记它,只要您不更改基本对象的框架即可。变换等会影响子层,因此您可以缩放、旋转等而不会出现粗糙的边缘。
希望这可以帮到您!

3
创建一个类似这样的自定义边框:

    UIImage *image = [UIImage imageNamed:@"spongebob.jpg"];
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 200, 200)];
    [borderView.layer setMasksToBounds:YES];
    [borderView.layer setCornerRadius:borderView.frame.size.width/2.0f];
    [borderView setBackgroundColor:[UIColor whiteColor]];

    int borderWidth = 3.0f;

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(borderWidth, borderWidth, borderView.frame.size.width-borderWidth*2, borderView.frame.size.height-borderWidth*2)];
    [imageView.layer setCornerRadius:imageView.frame.size.width/2.0f];
    [imageView.layer setMasksToBounds:YES];
    [imageView setImage:image];
    [borderView addSubview:imageView];


    [self.view addSubview:borderView];

现在你的图片不会突破边框了。

在这里输入图片描述

希望这能帮到你 :)

我认为仅使用UIImageView是没有办法的。 - Ty Lertwichaiworawit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接