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

时间:2014-08-23 23:10:00

标签: ios objective-c uiimageview

我试图制作一个带有圆角和白色边框的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 个答案:

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

希望这有帮助!

答案 1 :(得分: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];

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

enter image description here

希望这会有所帮助:)