【问题标题】:UIImageView with border and rounded corner with image pops out from the border edges带有边框的 UIImageView 和带有图像的圆角从边框边缘弹出
【发布时间】:2014-08-23 23:10:00
【问题描述】:

我正在尝试制作一个带有圆角和白色边框的 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

这是结果:

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

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

【问题讨论】:

    标签: ios objective-c uiimageview


    【解决方案1】:

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

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

    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 子类中。只要不更改基础对象的框架,您就可以为对象添加边框并忘记它。变换等会影响子层,因此您可以缩放、旋转等,而不会产生毛边。

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      像这样创建自定义边框:

          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
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      相关资源
      最近更新 更多