i'm trying to make a UIImageView with rounder corner and white border, i have subclassed a 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:
seems fine, but there is a problem as you can see from here:
the image pops out from the borders edge, how i can avoid this problem? how i can cut the image exactly at the edge of the border?
Perhaps a better solution doesn't involve making another View at all - with two views you greatly increase complexity for animation etc, not to mention overhead to keep track of and manipulate both.
I'd instead create a shape layer and add it as a sublayer. Something like this:
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)
The benefit of doing it this way is that you can add it as a method on your UIImageView subclass if you wish. You can add a border to an object and forget about it, as long as you're not changing the frame of the base object. Transforms etc affect sublayers so you can scale, rotate, etc and not have gross edges.
Hope this helps!
Create a custom border like this:
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 image does not pop out of the border.
Hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With