view.mask 遮罩,或者刮奖效果的核心属性
2017-04-14 本文已影响116人
Heikki_
https://github.com/pgorzelany/ScratchCardView
这有一个实现刮奖效果的第三方,一个灰色遮罩,手指划过会显现图片内容.
如图:
看到效果第一时间,认为是在imageView 上方遮盖一层灰色 View ,在手指划过时,路径变成透明,以达到效果.当然,现实中是这样实现的没错.
但是,在运行 demo 时,看到层级结构
当相关如下时:
效果 层级结构 ????
顶着崩坏的世界观继续看源码
直到
canvasMaskView.backgroundColor = UIColor.clear
canvasMaskView.strokeColor = UIColor.orange
canvasMaskView.lineWidht = scratchWidth
contentViewContainer.mask = canvasMaskView
canvasMaskView 即 我写了 Hi 的图层
mask 是什么属性? 点击去还是系统的属性?
于是去百了个度 看到文章
http://www.jianshu.com/p/e4ac8266d9f0
恍然大悟! 我的世界观得以修正,谢谢!
说:
UIView有一个maskView属性(遮罩),这个属性是通过改变alpha通道来改变透明度的,可以理解为maskview将自己“投影”到view上,实现改变alpha一样的效果。
1.设置了遮罩属性后view只显示和遮罩重叠的区域。
2.通过改变遮罩的alpha和颜色实现透明、半透明的效果。
至于划线部分.代码非常简单(以下为框架:ScratchCardView 中摘抄)
import UIKit
class CanvasView: UIView {
// MARK: Properties
@IBInspectable var lineWidht: CGFloat = 1
@IBInspectable var strokeColor = UIColor.red
fileprivate var paths: [CGMutablePath] = []
fileprivate var currentPath: CGMutablePath?
// MARK: Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configureView()
}
init(strokePaths paths: [CGMutablePath]) {
self.init()
self.paths = paths
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
for path in self.paths + [self.currentPath].flatMap({$0}) {
context?.addPath(path)
context?.setLineWidth(lineWidht)
context?.strokePath()
}
}
// MARK: Actions
func panGestureRecognized(_ recognizer: UIPanGestureRecognizer) {
let location = recognizer.location(in: self)
switch recognizer.state {
case .began:
self.beginPath(at: location)
case .changed:
self.addLine(to: location)
default:
self.closePath()
}
}
// MARK: Public methods
func beginPath(at point: CGPoint) {
self.currentPath = CGMutablePath()
self.currentPath?.move(to: point)
}
func addLine(to point: CGPoint) {
self.currentPath?.addLine(to: point)
self.setNeedsDisplay()
}
func closePath() {
if let currentPath = self.currentPath {
self.paths.append(currentPath)
}
self.currentPath = nil
self.setNeedsDisplay()
}
func clear() {
self.paths = []
self.setNeedsDisplay()
}
// MARK: Private Methods
fileprivate func configureView() {
self.addGestureRecognizers()
}
fileprivate func addGestureRecognizers() {
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognized))
self.addGestureRecognizer(panRecognizer)
}
}