Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fade the corners/edges/borders of a UIImageView

I was unable to find this on the forums so I decided to post this.

I have a UIImageView with the following code which fades the images from one another.

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];

imageNames = [NSArray arrayWithObjects:@"image1.jpg", @"image2.jpg", @"image3.jpg", @"image4.jpg", @"image5.jpg", nil];
imageview.image = [UIImage imageNamed:[imageNames objectAtIndex:0]];
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(transitionPhotos) userInfo:nil repeats:YES];

// Rounds corners of imageview
CALayer *layer = [imageview layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:5];

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

-(void)transitionPhotos{

if (photoCount < [imageNames count] - 1){
    photoCount ++;
}else{
    photoCount = 0;
}
[UIView transitionWithView:imageview
                  duration:2.0
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{imageview.image = [UIImage imageNamed:[imageNames objectAtIndex:photoCount]]; }
                completion:NULL];
}

I want to implement a code that will fade the borders of my imageview.

I know I can use the QuartzCore.framework, however I was unable to find a guide how to achieve the result that I want.

What would be the shortest possible code to do such a method?

like image 509
user3699052 Avatar asked Jul 13 '14 11:07

user3699052


1 Answers

Have an image containing a mask (blurred rectangle on transparent background):

UIImage *mask = [UIImage imageNamed:@"mask.png"];

create a maskLayer:

CALayer *maskLayer = [CALayer layer];
maskLayer.contents = (id)mask.CGImage;
maskLayer.frame = imageView.bounds;

and assign it as mask for your imageView:

imageView.layer.mask = maskLayer;

Edit: you can create the mask completely by code using the shadow properties of CALayer. Just play around with shadowRadius and shadowPath:

CALayer *maskLayer = [CALayer layer];
maskLayer.frame = imageView.bounds;
maskLayer.shadowRadius = 5;
maskLayer.shadowPath = CGPathCreateWithRoundedRect(CGRectInset(imageView.bounds, 5, 5), 10, 10, nil);
maskLayer.shadowOpacity = 1;
maskLayer.shadowOffset = CGSizeZero;
maskLayer.shadowColor = [UIColor whiteColor].CGColor;

imageView.layer.mask = maskLayer; 
like image 177
robert Avatar answered Nov 14 '22 19:11

robert