繁体   English   中英

带有边框的UIImageView和带有图像的圆角从边框边缘弹出

[英]UIImageView with border and rounded corner with image pops out from the border edges

我正在尝试用更圆角和白色边框制作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

这是结果:

在此输入图像描述

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

在此输入图像描述

图像从边框边缘弹出,我怎么能避免这个问题? 我怎样才能在边界边缘准确切割图像?

也许更好的解决方案不涉及制作另一个视图 - 使用两个视图可以大大增加动画等的复杂性,更不用说跟踪和操纵两者的开销。

我会创建一个形状图层并将其添加为子图层。 像这样的东西:

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子类的方法添加。 只要您不更改基础对象的框架,就可以向对象添加边框并将其遗忘。 变换等会影响子图层,因此您可以缩放,旋转等,而不会产生粗糙边缘。

希望这可以帮助!

像这样创建一个自定义边框:

    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];

现在你的图像没有弹出边界。

在此输入图像描述

希望这可以帮助 :)

暂无
暂无

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

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