要讓一個 view 顯示圓角,只需要三行程式碼:
CALayer *layer = [avatarImageView layer]; [layer setMasksToBounds:YES]; [layer setCornerRadius:9.0];
照直覺把陰影屬性也設上去:
avatarImageView.layer.shadowColor = [UIColor blackColor].CGColor; avatarImageView.layer.shadowOffset = CGSizeMake(0, 1); avatarImageView.layer.shadowOpacity = 1;
結果什麼都看不到。原因很直接:masksToBounds = YES 會裁掉所有超出自身邊界(bounds)的內容,而陰影正是畫在 view 邊界之外的,於是被一起裁掉了。圓角與陰影因此互相衝突。
把圓角的 imageView 放進一個尺寸相同的容器 view,讓容器負責畫陰影,視覺效果就跟直接加陰影一樣。
CGRect rect = CGRectMake(0, 0, 48, 48); avatarImageView = [[UIImageView alloc] initWithFrame:rect]; avatarImageView.image = [UIImage imageNamed:@"test.png"]; // 1. 讓 imageView 呈現圓角 CALayer *layer = [avatarImageView layer]; [layer setMasksToBounds:YES]; [layer setCornerRadius:9.0]; // 2. 建立同尺寸的容器負責陰影 UIView *shadow = [[UIView alloc] initWithFrame:rect]; avatarImageView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height); 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; // 容器絕對不能裁剪 // 3. 組合 [shadow addSubview:avatarImageView];
關鍵在最後那行 shadow.clipsToBounds = NO。容器的 cornerRadius 只是讓陰影形狀跟著圓角走,並不影響子 view 的裁剪行為。
除了包裝容器,也可以打開 masksToBounds 並改用 shadowPath。指定 shadowPath 之後,Core Animation 不需要依 alpha 運算陰影輪廓,效能明顯更好:
avatarImageView.layer.masksToBounds = NO;
avatarImageView.layer.shadowColor = [UIColor blackColor].CGColor;
avatarImageView.layer.shadowOffset = CGSizeMake(0, 2);
avatarImageView.layer.shadowOpacity = 0.5;
avatarImageView.layer.shadowRadius = 4.0;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:
avatarImageView.bounds cornerRadius:9.0];
avatarImageView.layer.shadowPath = path.CGPath;
不過這個做法有個限制:因為 masksToBounds 關閉,若圖片本身沒有圓角,圖片會是方的。因此圖片本身必須已經是圓角圖,或改用 CAShapeLayer 做 mask。
若同時需要「圖片圓角」與「陰影」,最推薦的組合是:用 imageView 的 layer.cornerRadius 加 layer.masksToBounds 處理圓角,另外用一個 CAShapeLayer 或 layer.shadowPath 畫在同一 layer 上;或者直接外包一個容器 view 承擔陰影,也就是本文第二節的包裝法。兩者都能兼顧視覺與效能,其中 shadowPath 因為避免了離屏渲染,在列表滾動場景下差異會很明顯。
最後提醒:在 UIScrollView 或 UITableViewCell 中使用陰影時,務必在 layoutSubviews 中依最新 bounds 更新 shadowPath,否則旋轉或尺寸變動後陰影會與內容錯位。