前言:
原作者地址:https://github.com/Mstic/inner_shadow
我这是从原作者改写过来的Swift版本。
花了点时间搜了一下iOS内阴影相关的文章。结果项目里没有用上,背景用的是一个图片拉伸的。
代码地址:
代码地址:https://gitee.com/yuency/Autolayout
示例代码类名 【InnerShadowView】【InnerShadowViewController】
效果图:
内阴影.PNG
上代码!
InnerShadowView.swift
import UIKit
class InnerShadowView: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
backgroundColor?.getRed(&r, green: &g, blue: &b, alpha: &a)
let color = UIColor(red: r, green: g, blue: b, alpha: a)
let shadow = NSShadow()
shadow.shadowColor = UIColor(cgColor: layer.shadowColor ?? UIColor.black.cgColor)
shadow.shadowOffset = layer.shadowOffset
shadow.shadowBlurRadius = layer.shadowRadius
let rectanglePath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius)
color.setFill()
context?.saveGState()
context?.clip(to: rectanglePath.bounds)
context?.setShadow(offset: .zero, blur: 0, color: nil)
context?.setAlpha((shadow.shadowColor as! UIColor).cgColor.alpha)
context?.beginTransparencyLayer(auxiliaryInfo: nil)
let opaqueShadow = (shadow.shadowColor as! UIColor)
context?.setShadow(offset: shadow.shadowOffset, blur: shadow.shadowBlurRadius, color: opaqueShadow.cgColor)
context?.setBlendMode(.sourceOut)
context?.beginTransparencyLayer(auxiliaryInfo: nil)
opaqueShadow.setFill()
rectanglePath.fill()
context?.endTransparencyLayer()
context?.endTransparencyLayer() //这句不多余
context?.restoreGState()
}
}
调用示例:
import UIKit
class InnerShadowViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
//使用
let shadowView_1 = InnerShadowView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
shadowView_1.backgroundColor = UIColor.white
shadowView_1.layer.cornerRadius = 100
shadowView_1.clipsToBounds = true
shadowView_1.layer.shadowColor = UIColor.black.cgColor
shadowView_1.layer.shadowOffset = CGSize(width: 5, height: 5)
shadowView_1.layer.shadowRadius = 20
self.view.addSubview(shadowView_1)
let shadowView_2 = InnerShadowView(frame: CGRect(x: 100, y: 333, width: 200, height: 200))
shadowView_2.backgroundColor = UIColor.white
shadowView_2.layer.shadowColor = UIColor.black.cgColor
shadowView_2.layer.shadowOffset = CGSize(width: 0, height: 0)
shadowView_2.layer.shadowRadius = 20
self.view.addSubview(shadowView_2)
let shadowView_3 = InnerShadowView(frame: CGRect(x: 100, y: 600, width: 200, height: 100))
shadowView_3.backgroundColor = UIColor.white
shadowView_3.layer.cornerRadius = 50
shadowView_3.clipsToBounds = true
shadowView_3.layer.shadowColor = UIColor.black.cgColor
shadowView_3.layer.shadowOffset = CGSize(width: 0, height: 0)
shadowView_3.layer.shadowRadius = 20
self.view.addSubview(shadowView_3)
}
}
结语
有待改进,设置阴影的透明度。
网友评论