UIImageView with a border and rounded corner with the image floats out of the border faces

I'm trying to make a UIImageView with an angular angle and a white border, I have subclassed UIImageView, this is the code:

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

this is the result:

enter image description here

seems fine, but there is a problem, as you can see here:

enter image description here

the image comes out of the edge of the borders, how can I avoid this problem? How can I crop the image exactly on the edge of the border?

+4
source share
2 answers

Create a custom border as follows:

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

Now you do not go out of the frame.

enter image description here

Hope this helps :)

+3
source

, - .., , .

. - :

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, . , . .. , , .., .

, !

+4

All Articles