无法使UIButton的图层蒙版生效

时间:2016-06-16 16:01:16

标签: ios swift uibutton calayer

我无法掩盖UIButton。它适用于UIView,但不适用于UIButton。

我的代码非常简单:

let maskingLayer = CALayer()
maskingLayer.frame = backToLiveButton.bounds
let maskingImage = WxStyleKit.imageOfTimelineBackToLiveArrow(backToLiveButton.bounds)
maskingLayer.contents = maskingImage.CGImage
backToLiveButton.layer.mask = maskingLayer

你有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

我能够通过继承UIButton并覆盖drawRect来使掩蔽工作。有两个选项可以使其工作,要么将图像转换为UIImage,要么修改PaintCode函数以返回UIBezierPath并使用CAShapeLayer

选项1:使用预定义图像

class MaskedButton: UIButton {

  @IBInspectable var imageString: String?

  override func draw(_ rect: CGRect) {
    super.draw(rect)
    if let imageString = imageString {
      let maskImage = UIImage(imageLiteralResourceName: imageString)
      let maskImageView = UIImageView(frame: rect)
      maskImageView.contentMode = .scaleAspectFit
      maskImageView.image = maskImage
      layer.mask = maskImageView.layer
    }
  }

}

在此方法中,imageString属性在Interface Builder中设置,并且是Assets.xcassets中图像的名称。

选项2:使用动态创建的UIBezierPath

class MaskedButton: UIButton {

  override func draw(_ rect: CGRect) {
    super.draw(rect)
    let maskLayer = CAShapeLayer()
    maskLayer.path = Wx.drawCanvas1(frame: rect).cgPath
    layer.mask = maskLayer
  }

}

修改后的PaintCode函数

public class Wx : NSObject {

   //// Drawing Methods

   public class func drawCanvas1(frame: CGRect) -> UIBezierPath {

       //// Bezier Drawing
       let bezierPath = UIBezierPath()
       bezierPath.move(to: CGPoint(x: frame.minX + 8.88, y: frame.minY + 28.28))
       bezierPath.addCurve(to: CGPoint(x: frame.minX + 77.2, y: frame.minY + 1.57), controlPoint1: CGPoint(x: frame.minX + 32.99, y: frame.minY + 2.6), controlPoint2: CGPoint(x: frame.minX + 63.13, y: frame.minY - 4.59))
       ...
       bezierPath.close()

       return bezierPath
    }

}

此方法有效,但不幸的是,您必须为每种类型的按钮创建一个子类,因为它依赖于drawRect覆盖中的函数。我不知道动态设置函数调用的任何方法,但我希望这有帮助!

如果您有任何疑问,请随时提出!