xyk blog

最近は iOS 開発の記事が多めです。

角丸なUIViewに角丸な影をつける

環境: Swift3

角丸なUIViewに角丸なドロップシャドウをつけるやり方。

shadowView.layer.cornerRadius = 10
shadowView.layer.masksToBounds = false

shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 5, height: 5) // 影の方向(ここでは右下)
shadowView.layer.shadowOpacity = 0.5 // 影の濃さ
shadowView.layer.shadowRadius = 5 // 影のぼかし量

f:id:xyk:20170319023445p:plain

プレイグラウンドで確認。

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor(red: 255/255, green: 110/255, blue: 134/255, alpha: 1)

let shadowView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
shadowView.backgroundColor = UIColor(red: 89/255, green: 172/255, blue: 255/255, alpha: 1)
shadowView.center = view.center

shadowView.layer.cornerRadius = 10
shadowView.layer.masksToBounds = false

shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 5, height: 5)
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.shadowRadius = 5

// 以下、角丸パス追加とラスタライズで高速化
shadowView.layer.shadowPath = UIBezierPath(roundedRect: shadowView.bounds, cornerRadius: 10).cgPath
shadowView.layer.shouldRasterize = true
shadowView.layer.rasterizationScale = UIScreen.main.scale

view.addSubview(shadowView)

PlaygroundPage.current.liveView = view

例2:
ぼんやりしてない影をちょっとだけをつけたい場合
shadowRadius を小さくするすると以下のようなかんじになった。

f:id:xyk:20190308150318p:plain

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .groupTableViewBackground

let shadowView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
shadowView.backgroundColor = .white
shadowView.center = view.center

shadowView.layer.cornerRadius = 10
shadowView.layer.masksToBounds = false

shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 2, height: 2)
shadowView.layer.shadowOpacity = 0.1
shadowView.layer.shadowRadius = 0

view.addSubview(shadowView)

PlaygroundPage.current.liveView = view

StackOverFlowにわかりやすいサンプル例があったので転載。

stackoverflow.com f:id:xyk:20190308151603p:plain