在 ios 开发中,最怕看到设计稿里圆角、阴影和边框同时出现,这三兄弟简直就是性能杀手。
优化的方法百度一下有很多,虽然方法不同但是原理都一样。
分享一个我自己一直使用的方法:在一个 view 里只应用一种效果,然后通过组合的方式达到效果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
override init(frame: cgrect) {
super.init(frame: frame)
imageview = uiimageview(image: uiimage(named: "img" ))
imageview.layer.cornerradius = 14
imageview.layer.maskstobounds = true
backgroundview = imageview
shadowview = shadowview()
shadowview.layer.cornerradius = 20
shadowview.applyshadow(.black, cgsize(width: 0, height: 15), 0.2, 40)
insertsubview(shadowview, belowsubview: imageview)
contentview.layer.cornerradius = 14
contentview.layer.borderwidth = 1
contentview.layer.bordercolor = uicolor.orange.cgcolor
contentview.layer.maskstobounds = true
}
|
层次结构:
- contentview: 描绘边框,放在最上层。
- imageview: 显示圆角,放在中间,用于背景图。
- shadowview: 显示阴影,放在最底层。代码很简单,只是封装了一下阴影参数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
class shadowview: uiview {
private var shadowcolor: uicolor?
private var shadowopacity: cgfloat = 1
private var shadowoffset: cgsize = cgsize(width: 0, height: 3)
private var shadowblur: cgfloat = 6
override func layoutsubviews() {
super.layoutsubviews()
updateshadow()
}
func applyshadow(_ color: uicolor?, _ offset: cgsize, _ opacity: cgfloat, _ blur: cgfloat) {
shadowcolor = color
shadowoffset = offset
shadowopacity = opacity
shadowblur = blur
updateshadow()
}
private func updateshadow() {
layer.shadowcolor = shadowcolor?.cgcolor
layer.shadowoffset = shadowoffset
layer.shadowopacity = float (shadowopacity)
layer.shadowradius = shadowblur * 0.5
layer.shadowpath = uibezierpath(roundedrect: self.bounds, cornerradius: layer.cornerradius).cgpath
}
}
|
分开单独绘制速度很快,使用 uicollectionview 进行滚动测试,生成的 cell 数量是 1 万个。
测试机器是 5s + ios 12.4.4,快速滑动无任何卡顿。
给一个测试 demo 大家体验一下:
github:shadow_view_demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://juejin.im/post/5e19ea4ee51d4501fa4679c3