讓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]; 圓角陰影效果就出來了。