Skip to content

Instantly share code, notes, and snippets.

@soemarko
Created January 11, 2018 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soemarko/a7f6c4d67028df27d09edaf3384ecbd5 to your computer and use it in GitHub Desktop.
Save soemarko/a7f6c4d67028df27d09edaf3384ecbd5 to your computer and use it in GitHub Desktop.
Swift version of [AKStencilButton](https://github.com/kas-kad/AKStencilButton)
import UIKit
class ClearTextButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("This view doesn't support NSCoding")
}
override func setTitleColor(_ color: UIColor?, for state: UIControlState) {
super.setTitleColor(color, for: state)
}
override func layoutSubviews() {
super.layoutSubviews()
self.refreshMask()
}
private func setup() {
self.backgroundColor = UIColor.groupTableViewBackground
self.clipsToBounds = true
}
private func refreshMask() {
self.titleLabel?.backgroundColor = UIColor.clear
self.setTitleColor(UIColor.clear, for: .normal)
let text: String? = self.titleLabel?.text
let buttonSize: CGSize = self.bounds.size
let font: UIFont? = self.titleLabel?.font
let textSize: CGSize? = text?.size(withAttributes: [NSAttributedStringKey.font: (self.titleLabel?.font)!])
UIGraphicsBeginImageContextWithOptions(buttonSize, false, UIScreen.main.scale)
let ctx: CGContext? = UIGraphicsGetCurrentContext()
ctx?.setFillColor(UIColor.white.cgColor)
let center = CGPoint(x: buttonSize.width / 2 - (textSize?.width)! / 2, y: buttonSize.height / 2 - (textSize?.height)! / 2)
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: buttonSize.width, height: buttonSize.height))
ctx?.addPath(path.cgPath)
ctx?.fillPath()
ctx!.setBlendMode(.destinationOut)
text?.draw(at: center, withAttributes: [NSAttributedStringKey.font: font!])
let viewImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = viewImage?.cgImage as Any
maskLayer.frame = bounds
layer.mask = maskLayer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment