如下图所示,非纯色背景上有文字滑动。类似于直播间的公屏聊天区域,实现滑入滑出有模糊效果

代码如下:

  • 把内容的scrollview包裹在带渐变mask的父view上即可
  • mask有颜色就是透明的,alpha是反着的
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
lazy var contentParentView: UIView = {
let view = UIView()
view.backgroundColor = .clear
return view
}()

private lazy var contentWebView: WKWebView = {
let config: WKWebViewConfiguration = WKWebViewConfiguration()
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: UIDevice.screenWidth - 32, height: 10), configuration: config)
webView.scrollView.isMultipleTouchEnabled = false
webView.scrollView.showsVerticalScrollIndicator = false
webView.isOpaque = false
webView.backgroundColor = UIColor.clear
webView.scrollView.backgroundColor = UIColor.clear
webView.scrollView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
if #available(iOS 11.0, *) {
webView.scrollView.contentInsetAdjustmentBehavior = .never
} else {
self.automaticallyAdjustsScrollViewInsets = false
}
return webView
}()

contentParentView.addSubview(contentWebView)
contentWebView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}

if let practiceModel = practiceModel {
let blurTransformer = SDImageBlurTransformer(radius: 40)
blurBgImageView.sd_setImage(with: URL(string: practiceModel.coverUrl), placeholderImage: nil, context: [.imageTransformer: blurTransformer])
titleLabel.text = practiceModel.title
countLabel.text = "\(practiceModel.submitTimes)人练习过"

loadWebContent(html: practiceModel.content)
}

let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(x: 0, y: 0, width: self.contentParentView.width, height: self.contentParentView.height)
gradientLayer.colors = [UIColor.white.withAlphaComponent(0).cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.white.withAlphaComponent(0).cgColor]
gradientLayer.locations = [0, 0.1, 0.9, 1]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
contentParentView.layer.mask = gradientLayer

func loadWebContent(html: String) {
let htmlString = "<head><meta name='viewport' content='width=device-width,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'><style>p,span,h1,h2,h3,h4,h5,h6,h7,b,div{color: #FFF !important;}</style></head><body>\(html)</body>"
contentWebView.loadHTMLString(htmlString, baseURL: nil)
}