让UIView圆角显示很简单,只需要三行代码
CALayer * layer = [avatarImageView layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:9.0];
但是,如给给圆角view加阴影,传统加阴影的方法是不行的,
传统的方法就是:
avatarImageView.layer.shadowColor = [UIColor blackColor].CGColor;
avatarImageView.layer.shadowOffset = CGSizeMake(0, 1);
avatarImageView.layer.shadowOpacity = 1;
因为setMasksToBounds表示对frame外的内容进行了裁减,只可显示frame内的内容。由于这种方法加的阴影在frame外,所以被裁减了。
传统方法不行,那我们可以把圆角的avatarImageView放到一个大小与它一样的的UIView中,让这个view有阴影,那效果看起来就一样了。
CGRect rect;
rect = CGRectMake(0, 0, 48, 48);
avatarImageView = [[UIImageView alloc] initWithFrame:rect];
avatarImageView.image = [UIImage imageNamed:@"test.png"];
//Round the corners
CALayer * layer = [avatarImageView layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:9.0];
//Add a shadow by wrapping the avatar into a container
UIView * shadow = [[UIView alloc] initWithFrame: rect];
avatarImageView.frame = CGRectMake(0,0,rect.size.width, rect.size.height);
// setup shadow layer and corner
shadow.layer.shadowColor = [UIColor grayColor].CGColor;
shadow.layer.shadowOffset = CGSizeMake(0, 1);
shadow.layer.shadowOpacity = 1;
shadow.layer.shadowRadius = 9.0;
shadow.layer.cornerRadius = 9.0;
shadow.clipsToBounds = NO;
// combine the views
[shadow addSubview: avatarImageView];
圆角阴影效果就出来了。