https://github.com/pgorzelany/ScratchCardView
這有一個實現(xiàn)刮獎效果的第三方,一個灰色遮罩,手指劃過會顯現(xiàn)圖片內(nèi)容.
如圖:
看到效果第一時間,認為是在imageView 上方遮蓋一層灰色 View ,在手指劃過時,路徑變成透明,以達到效果.當然,現(xiàn)實中是這樣實現(xiàn)的沒錯.
但是,在運行 demo 時,看到層級結(jié)構(gòu)
當相關(guān)如下時:
頂著崩壞的世界觀繼續(xù)看源碼
直到
canvasMaskView.backgroundColor = UIColor.clear
canvasMaskView.strokeColor = UIColor.orange
canvasMaskView.lineWidht = scratchWidth
contentViewContainer.mask = canvasMaskView
canvasMaskView 即 我寫了 Hi 的圖層
mask 是什么屬性? 點擊去還是系統(tǒng)的屬性?
于是去百了個度 看到文章
http://www.reibang.com/p/e4ac8266d9f0
恍然大悟! 我的世界觀得以修正,謝謝!
說:
UIView有一個maskView屬性(遮罩),這個屬性是通過改變alpha通道來改變透明度的荷并,可以理解為maskview將自己“投影”到view上,實現(xiàn)改變alpha一樣的效果。
1.設(shè)置了遮罩屬性后view只顯示和遮罩重疊的區(qū)域呜达。
2.通過改變遮罩的alpha和顏色實現(xiàn)透明颂郎、半透明的效果膘茎。
至于劃線部分.代碼非常簡單(以下為框架: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)
}
}